#!/bin/bash
#
# iscsi-devices		This shell script takes care of starting and stopping iscsi.
#
# chkconfig:	2345 13 89
# description:	Start iSCSI devices
#
# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Source oident configureation.
if [ -f /etc/sysconfig/iscsi ]; then
	. /etc/sysconfig/iscsi
fi

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "iSCSI devices"
		exit 1
	fi
else
	exit 0
fi

start() {
	# Start daemons.
	if [ ! -f /var/lock/subsys/iscsi-devices ]; then
		# if no nodes are setup to startup automatically exit cleanly
		grep -qrs "node.startup = automatic" /etc/iscsi/nodes
		[ $? -eq 0 ] || exit 0

		msg_starting "iSCSI devices"; busy
		iscsiadm -m node --loginall=automatic 2>&1 > /dev/null | grep iscsiadm

		# <sigh> iscsiadm does not always give a non 0 exit status in case of
		# error so we grep for any messages to stderr and see those as errors too
		if [ ${PIPESTATUS[0]} -ne 0 -o ${PIPESTATUS[1]} -eq 0 ]; then
			deltext; fail
			return 1
		fi

		deltext; ok
		touch /var/lock/subsys/iscsi-devices
	else
		msg_already_running "iSCSI devices"
	fi
}

stop() {
	# Stop daemons.
	if [ -f /var/lock/subsys/iscsi-devices ]; then
		msg_stopping "iSCSI devices"; busy
		iscsiadm -m node --logoutall=automatic 2>&1 > /dev/null | grep iscsiadm
		# <sigh> iscsiadm does not always give a non 0 exit status in case of
		# error so we grep for any messages to stderr and see those as errors too
		if [ ${PIPESTATUS[0]} -ne 0 -o ${PIPESTATUS[1]} -eq 0 ]; then
			deltext; fail
			return 1
		fi

		deltext; ok

		rm -f /var/lock/subsys/iscsi-devices >/dev/null 2>&1
	else
		msg_not_running "iSCSI devices"
	fi
}

condrestart() {
	if [ -f /var/lock/subsys/iscsi-devices ]; then
		stop
		start
	else
		msg_not_running "iSCSI devices"
		RETVAL=$1
	fi
}

RETVAL=0
case "$1" in
  start)
  	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	iscsiadm -m session
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
esac
exit $RETVAL
