#! /bin/sh
#
# Script Name : adpt-iscsi-umount
#
# Unmount all iSCSI devices that has been specified in the /etc/fstab.adaptec file
#

BASEDIR=/usr/local
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$BASEDIR/sbin:$BASEDIR/bin:$PATH
USAGE="Usage:\niscsi-umountall [-t] [-k]" 
MTAB=/etc/mtab 
FSTAB=/etc/fstab.adaptec
fslist=""

#
# Check to see if the /proc/mounts file exists.
# If it exists then assign this file to MTAB
#

if [ -e /proc/mounts ] ; then
    echo "/proc/mounts exists !"
    MTAB=/proc/mounts
fi

# defaults
terminate=
kill=

# get arguments
while getopts hskt c
do
        case $c in
        k)      kill="yes";;
        t)      terminate="yes";;
        h)      echo "$USAGE" 1>&2;
                exit 2;;
        esac
done
shift `expr $OPTIND - 1`

is_iscsi() # check for iSCSI devices
{
    if [ -e $FSTAB ]; then
	local dev mountp etc
	while read dev mountp etc
	do
	    case "$dev"
	    in
	    \#*) continue ;; #  ignore comments
	    '')  continue ;; # ignore empty lines
	    esac

	    if [ "$mountp" = $2 ]; then 
		return 0
	    fi
	done < $FSTAB
    fi
    return 1
}

#
# Read the /etc/MTAB file
#

cat $MTAB | tac | # process mtab in reverse order
{
    while read dev mountp fstype mode dummy dummy2
    do
	if is_iscsi $dev $mountp ; then
	    if [ "$terminate" ] || [ "$kill" ]; then # SIGTERM fs users 
		if fuser -k -TERM -m $mountp > /dev/null 2>&1; then
		    echo Waiting for users of $mountp to terminate
		    sleep 5
		fi
	    fi
	    if [ "$kill" ]; then # SIGKILL fs users
		if fuser -k -m $mountp > /dev/null 2>&1; then
		    echo Waiting for users of $mountp to exit
		    sleep 2
		fi
	    fi
	    
	    umount -r $mountp
	fi
   done
}
