#! /bin/sh
#
# Unmount all iSCSI devices.

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

if [ -e /proc/mounts ] ; then
    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;;
        *)      echo "$USAGE" 1>&2;
                exit 2;;
        esac
done
shift `expr $OPTIND - 1`

is_iscsi() # check for iSCSI devices
{
    if iscsi-device "$dev" > /dev/null 2>&1; then
	return 0
    fi

    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
}

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
}
