#! /bin/sh
### BEGIN INIT INFO
# Provides:          open-iscsi iscsi
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs sendsigs
# Default-Start:     S
# Default-Stop:      0 1 6
# Short-Description: Starts and stops the iSCSI initiator services and logs in to default targets
# Description:       Starts and stops the iSCSI initiator services and logs in to default targets
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/iscsid
ADM=/usr/bin/iscsiadm
PIDFILE=/run/iscsid.pid
NAMEFILE=/etc/iscsi/initiatorname.iscsi
CONFIGFILE=/etc/iscsi/iscsid.conf

[ -x "$DAEMON" ] || exit 0

. /lib/lsb/init-functions

# Include defaults if available
if [ -f /etc/default/open-iscsi ]; then
	. /etc/default/open-iscsi
fi


if [ ! -d /sys/class/ ]; then
  log_failure_msg "iSCSI requires a mounted sysfs, not started."
  exit 0
fi

nodestartup_re='s/^node\.conn\[0]\.startup[ 	]*=[ 	]*//p'

RETVAL=0

sanitychecks() {
        # Do sanity checks before we start..
        if [ ! -e "$CONFIGFILE" ]; then
                echo
                echo "Error: configuration file $CONFIGFILE is missing!"
                echo "The iSCSI driver has not been correctly installed and cannot start."
                echo
                exit 1
        elif [ -s $PIDFILE ] && kill -0 `head -1 $PIDFILE` >/dev/null ; then
		echo
                echo "iSCSI daemon already running"
                echo
                exit 0
        fi

        if [ ! -f $NAMEFILE ] ; then
            echo
            echo "Error: InitiatorName file $NAMEFILE is missing!"
            echo "The iSCSI driver has not been correctly installed and cannot start."
            echo
            exit 1
        fi

        # see if we need to generate a unique iSCSI InitiatorName
        # this should only happen if the
        if grep -q "^GenerateName=yes" $NAMEFILE ; then
            if [ ! -x /usr/sbin/iscsi-iname ] ; then
                echo "Error: /usr/sbin/iscsi-iname does not exist, driver was not successfully installed"
                exit 1;
            fi
            # Generate a unique InitiatorName and save it
            INAME=`/usr/sbin/iscsi-iname -p iqn.1993-08.org.debian:01`
            if [ "$INAME" != "" ] ; then
                echo "## DO NOT EDIT OR REMOVE THIS FILE!" > $NAMEFILE
                echo "## If you remove this file, the iSCSI daemon will not start." >> $NAMEFILE
                echo "## If you change the InitiatorName, existing access control lists" >> $NAMEFILE
                echo "## may reject this initiator.  The InitiatorName must be unique">> $NAMEFILE
                echo "## for each iSCSI initiator.  Do NOT duplicate iSCSI InitiatorNames." >> $NAMEFILE
                printf "InitiatorName=$INAME\n"  >> $NAMEFILE
                chmod 600 $NAMEFILE
            else
                echo "Error: failed to generate an iSCSI InitiatorName, driver cannot start."
                echo
                exit 1;
            fi
        fi

        # make sure there is a valid InitiatorName for the driver
        if ! grep -q "^InitiatorName=[^ \t\n]" $NAMEFILE ; then
            echo
            echo "Error: $NAMEFILE does not contain a valid InitiatorName."
            echo "The iSCSI driver has not been correctly installed and cannot start."
            echo
            exit 1
        fi
}

start() {
	log_daemon_msg "Starting iSCSI initiator service" "iscsid"
	sanitychecks
	modprobe -q iscsi_tcp 2>/dev/null || :
	modprobe -q ib_iser 2>/dev/null || :
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON
	RETVAL=$?
	log_end_msg $RETVAL

	starttargets

	udevadm settle || true;


	# Handle iSCSI LVM devices
	if [ ! -x "/sbin/vgchange" -a -n "$LVMGROUPS" ]; then
		log_warning_msg "LVM2 tools are not installed, not honouring LVMGROUPS."
		LMVGROUPS=""
	fi

	if [ -n "$LVMGROUPS" ]; then
		log_daemon_msg "Activating iSCSI volume groups"
		for vg in "$LVMGROUPS"; do
			log_progress_msg $vg
			vgchange --available=y $vg
		done
		log_end_msg 0
	fi

	# Now let's mount
	log_daemon_msg "Mounting network filesystems"
	MOUNT_RESULT=1
	if mount -a -O _netdev >/dev/null 2>&1; then
		MOUNT_RESULT=0
		break
	fi
	log_end_msg $MOUNT_RESULT
}

starttargets() {
	log_daemon_msg "Setting up iSCSI targets"
	echo
	$ADM -m node --loginall=automatic
	log_end_msg 0
}

stoptargets() {
	log_daemon_msg "Disconnecting iSCSI targets"
	sync
	# only logout if daemon is running, iscsiadm hangs otherwise
        if [ -s $PIDFILE ] && kill -0 `head -1 $PIDFILE` >/dev/null ; then
		$ADM -m node --logoutall=all
        fi

	log_end_msg 0
}

stop() {
	if [ -f /etc/iscsi/iscsi.initramfs ]; then
		log_warning_msg "/etc/iscsi/iscsi.initramfs present, not stopping iscsid yet"
		return 0
	fi

	# Call umountiscsi.sh to unmount iSCSI devices first
	invoke-rc.d umountiscsi.sh stop
	exit_status=$?
	if [ $exit_status -ne 0 ]; then
		log_failure_msg "Couldn't unmount all iSCSI devices. Cannot stop iSCSI service"
		exit 1
	fi

	stoptargets
	log_daemon_msg "Stopping iSCSI initiator service"
	start-stop-daemon --stop --quiet --pidfile $PIDFILE --signal TERM --exec $DAEMON
	rm -f $PIDFILE
	modprobe -r ib_iser 2>/dev/null
	modprobe -r iscsi_tcp 2>/dev/null
	log_end_msg 0
}

restart() {
	stop
	start
}

restarttargets() {
	stoptargets
	starttargets
}

status() {
	#XXX FIXME: what to do here?
	#status iscsid
	# list active sessions
	echo Current active iSCSI sessions:
	$ADM -m session
}

case "$1" in
	start|starttargets|stop|stoptargets|restart|restarttargets|status)
		$1
		;;
	force-reload)
		restart
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload|status}"
		exit 1
		;;
esac
exit $RETVAL
