#!/bin/sh

PID=$$
TMP_FILE=/tmp/netapp_san_inst_$PID
INS_DIR=/opt/netapp
INS_BIN_DIR=/opt/netapp/santools
DATE=`date +%Y%m%d_%H%M`
STANDARD_MAN_PATH=/usr/share/man/man1
latest_libdevmapper=""	# Global Variable to hold the latest libdevmapper.so.1.XX library filename.

# Ensure the user is running as root
USER=`/usr/bin/whoami`

if [ "$USER" != "root" ]
then
        echo
        echo "This install program must be run as root."
        echo
        exit 1
fi

# Function to get the latest libdevmapper.so.1.XX.
get_latest_libdevmapper () {
# Parse filenames and get the latest 1.XX filename.
	prevmin=0
	for i in $( find /lib -name 'libdevmapper.so.1.*' )
	do
		minor=`echo $i | awk -F. '{print $4}' | sed 's/0*//' | sed 's/[^[:digit:]]*//g'`
		if [ $minor -gt $prevmin ] ; then
			latest_libdevmapper=$i
			prevmin=$minor
		fi
	done
}

# The sanlun utility needs the 32 bit "/lib/libdevmapper.so"
# to be present on the host so that it can link
# to it and get multipathing information.
# Check if this is a SLES11 Host.
OS_RELEASE=0
if [ -f /etc/SuSE-release ]; then
	# Get the info from /etc/SuSE-release for SLES hosts
	OS_RELEASE=`cat /etc/SuSE-release | grep VERSION | sed 's/[^[:digit:]]*//g'`
fi
if [ $OS_RELEASE -eq 11 ] ; then
	# This is a SLES11 host.
	# Create a softlink in /lib to the device mapper
	# library /lib/libdevmapper.so.1.X if the library exists.
	# If it doesn't exist, error out and abort installing.
	if [ ! -f /lib/libdevmapper.so ] ; then
		get_latest_libdevmapper
		if [ ! -z $latest_libdevmapper ] ; then
			ln -s $latest_libdevmapper /lib/libdevmapper.so > /dev/null 2>&1
			if [ $? != 0 ]; then
				echo "ERROR: Creating softlink /lib/libdevmapper.so to the"
				echo "  device mapper library failed. Aborting installation."
				exit 1;
			fi
		else
			# The library libdevmapper.so.X doesnt exist.
			# sanlun needs the library to be present on the host.
			echo "ERROR: A component of the Linux Host Utilities requires the"
			echo "  32-bit libdevmapper library installed on the host. Please install"
			echo "  the 32-bit device mapper package which provides this library."
			exit 1;
		fi
	fi
fi

# See if there is already a sanlun installed 
if [ -d $INS_DIR ] ; then
	# There is an /opt/netapp/santools dir present move it aside
	echo "$INS_DIR exists, moving to $INS_DIR$DATE"
	/bin/mv $INS_DIR $INS_DIR$DATE
fi;

# create /opt/netapp/santools and install the stuff
/bin/mkdir -p $INS_BIN_DIR

# put all the stuff there
here=`pwd`
cd /; tar -xvf $here/sanlun_bin_netapp.tar

# make a link in /usr/sbin to sanlun
ln -s /opt/netapp/santools/sanlun /usr/sbin/sanlun > /dev/null 2>&1

# Now link the man pages into /usr/shared/man/man1 directory so that the man
# pages can be opened from anywhere.
ln -s /opt/netapp/man/man1/* $STANDARD_MAN_PATH > /dev/null 2>&1

exit 0;
