#!/bin/sh
#
# chkconfig: - 14 86
# description: Mount and unmount network block devices (iSCSI, AoE, ...)
#
# config:  /etc/fstab

### BEGIN INIT INFO
# Provides: netdev
# Required-Start: $network
# Required-Stop: $network
# Default-Start:
# Short-Description: Mount and unmount network block devices
# Description: Mount and unmount network block devices (iSCSI, AoE, ...)
### END INIT INFO

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/rc.d/init.d/functions

RETVAL=0

mount_nodes()
{
	sleep 5
	action 'Mounting netdev filesystems:' mount -a -O _netdev
	return 0
}

umount_all_luns()
{
    local d m dev p s

    cat /proc/mounts | sed -ne '/^\/dev\/.*/p' | while read d m t o x; do 
	if [ "$m" = "/" ] ; then 
	    continue;
	fi
	if [ -L "$d" ] ; then
	    d=$(readlink -f $d)
	fi
	dev=${d##/dev}

	if [ "${dev##/sd}" = "$dev" ] ; then
	    continue;
	fi
	p="/sys/block${dev%%[0-9]*}"

	if [ ! -d ${p} ] && [ ! -d ${p}/device ] ; then
	    continue;
	fi

	s=$(cd -P ${p}/device && echo $PWD)

	case "$s" in
	    */session[0-9]*/*)
		# This is an iSCSI device (FIXME: AoE?)
		echo -n "Unmount $m: "
		umount "$m"
		RETVAL=$?
		if [ $RETVAL == "0" ]; then
			echo_success
		else
			echo_failure
		fi
		echo
		#return 0
	    ;;
	esac
    done
}

start()
{
	modprobe -q iscsi_tcp
	modprobe -q ib_iser
        modprobe -q aoe
	mount_nodes
	return $RETVAL
}

stop()
{
	umount_all_luns
	modprobe -r iscsi_tcp 2>/dev/null
	modprobe -r ib_iser 2>/dev/null
	modprobe -r aoe 2>/dev/null
	return $RETVAL
}

restart()
{
	stop
	start
}

case "$1" in
	start)
	    start
	;;
	stop)
	    stop
	;;
	reload)
	    restart
	;;
	restart)
	    restart
	;;
	*)
	    msg_usage "${0##*/} {start|stop|reload|restart}"
	RETVAL=1
esac

exit $RETVAL