#!/bin/sh
#
# chkconfig: 345 39 35
# description: Starts and stops the iSCSI initiator
#
# pidfile: /var/run/iscsid.pid
# config:  /etc/iscsid.conf

### BEGIN INIT INFO
# Provides: open-iscsi
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 3 4 5
# Short-Description: iSCSI initiator
# Description: Starts and stops the iSCSI initiator
### END INIT INFO

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

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

ISCSID=`which iscsid`
ISCSIADM=`which iscsiadm`

if [ -z "$ISCSID" -o -z "$ISCSIADM" ]; then
    gprintf "open-iscsi not installed.\n"
    exit 1
fi

start_iscsid()
{
    RETVAL=0
    modprobe -q iscsi_tcp
    daemon $ISCSID
    RETVAL=$?
	if [ "$RETVAL" = "0" ]; then
	    TARGETS=`$ISCSIADM -m node | sed 's@\[\(.*\)\] .*@\1@g'`
	    for rec in $TARGETS; do
			STARTUP=`$ISCSIADM -m node -r $rec | grep "node.conn\[0\].startup" | cut -d' ' -f3`
			if [ $STARTUP = "automatic" ]; then
				$ISCSIADM -m node -r $rec -l
			fi
	    done
	fi
    return $RETVAL
}

stop_iscsid()
{
    RETVAL=0
    sync
    TARGETS=`$ISCSIADM | grep "\[*\]" | sed 's@\[\(.*\)\] .*@\1@g'`
	for rec in $TARGETS; do
		$ISCSIADM -m node -r $rec -u
    done
    # XXX - the pid file only has one pid, but we have two daemons
    killall -HUP `basename $ISCSID`
    RETVAL=$?
    modprobe -r iscsi_tcp 2>/dev/null
    return $RETVAL
}

start()
{
    RETVAL=0
    gprintf "Starting %s service: " "iSCSI initiator"
    PID=`pidofproc $ISCSID`
    if [ -z $PID ]; then
        start_iscsid
    fi
	if [ $RETVAL == "0" ]; then
        echo_success
		touch /var/lock/subsys/iscsid
    else
        echo_failure
    fi
    echo
    return $RETVAL
}

stop()
{
    gprintf "Stopping %s service: " "iSCSI initiator"
    PID=`pidofproc $ISCSID`
	RETVAL=$?
	if [ -n "$PID" ]; then
        stop_iscsid
    fi
	if [ "$RETVAL" == "0" ]; then
        echo_success
		rm -f /var/lock/subsys/iscsid
		rm -f /var/run/iscsid.pid
    else
        echo_failure
    fi
    echo
    return $RETVAL
}


restart()
{
    stop
    start
	return $?
}


case "$1" in
  start)
        start
		RETVAL=$?
        ;;
  stop)
        stop
		RETVAL=$?
        ;;
  restart)
        restart
		RETVAL=$?
        ;;
  status)
		status `basename $ISCSID`
		RETVAL=$?
        ;;
  *)
        gprintf "Usage: %s {start|stop|restart|status}\n" "open-iscsi"
        exit 1
esac

exit $RETVAL
