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

# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 0
fi

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

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

if [ -z $ISCSID ] || [ -z $ISCSIADM ]
then
    echo "open-iscsi not installed."
    exit 1
fi

start_iscsid()
{
    RETVAL=0
    modprobe -q iscsi_tcp
    daemon $ISCSID
    RETVAL=$?
    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
    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
    pkill -KILL `basename $ISCSID`
    modprobe -r iscsi_tcp
    RETVAL=$?
    return $RETVAL
}

start()
{
    RETVAL=0
    echo -n "Starting iSCSI initiator service: "
    PID=`pidofproc $ISCSID`
    if [ -z $PID ]
    then
        start_iscsid
    fi
    if [ $RETVAL == "0" ]
    then
        echo_success
    else
        echo_failure
    fi
    echo
    return $RETVAL
}

stop()
{
    RETVAL=0
    echo -n "Stopping iSCSI initiator service: "
    PID=`pidofproc $ISCSID`
    if [ $PID ]
    then
        stop_iscsid
    fi
    if [ $RETVAL == "0" ]
    then
        echo_success
    else
        echo_failure
    fi
    echo
    return $RETVAL
}


restart()
{
    stop
    start
}

status()
{
    PID=`pidofproc $ISCSID`
    if [ ! $PID ]
    then
        echo "iSCSI initiator is stopped."
        exit 1
    else
        echo "iSCSI initiator is running."
    fi
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  status)
        status
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|status}"
        exit 1
esac

exit 0
