#!/bin/sh
#
# chkconfig: - 39 35
#
### BEGIN INIT INFO
# Provides:          tgtd
# Required-Start:    $network
# Short-Description: Starts and stops the generic storage target daemon
# Description: tgtd provides the SCSI and software transport target state
#              machine daemon.
### END INIT INFO
#
#
# pidfile: /var/run/tgtd.pid
#
# Source function library.
. /etc/init.d/functions

# Check for and source configuration file otherwise set defaults
[ -f /etc/sysconfig/tgtd ] && . /etc/sysconfig/tgtd

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

RETVAL=0

[ -z "${TGTD_CONFIG}" ] && {
	TGTD_CONFIG="/etc/tgt/targets.conf"
}

# We will not support FCOE in this release
#[ -z "${TGTD_FCOE}" ] || {
#	TGTD_OPTIONS="$TGTD_OPTIONS $TGTD_FCOE"
#}


start()
{
	echo -n $"Starting SCSI target daemon: "
	if [ -f /var/lock/subsys/tgtd ]; then
		success
		echo
		return
	fi

	# check we have a config
	[ ! -f "${TGTD_CONFIG}" ] && {
		echo $"Configuration file ${TGTD_CONFIG} is missing"
		failure
		RETVAL=1
		return
	}

	daemon tgtd $TGTD_OPTIONS

	# read the config 
	tgt-admin -e -c "${TGTD_CONFIG}"
	RETVAL=$?
	[ $RETVAL -ne 0 ] && {
		tgtadm --op delete --mode system
		failure
		return
	}

	echo
	touch /var/lock/subsys/tgtd
}

stop()
{
	echo -n $"Stopping SCSI target daemon: "

	if [ ! -f /var/lock/subsys/tgtd ]; then
		success
		echo
		return
	fi

	if tgtadm --op show -m target | grep "Target" >/dev/null ; then
		if [ "$RUNLEVEL" = "6" -o "$RUNLEVEL" = "0" -o "$RUNLEVEL" = "1" ]; then
			# if the system is going down force the shutdown
			# so the shutdown does not hang
			tgt-admin --delete ALL --force
		else
			tgt-admin --delete ALL
			# must check for running targets here
		fi
	fi

	# shut down tgtd
	tgtadm --op delete --mode system
	RETVAL=$?
	[ $RETVAL -ne 0 ] && {
		echo $"Failed to shutdown target"
		failure
		RETVAL=1
		return
	}

	rm -f /var/lock/subsys/tgtd
	success
	echo
}

# this will kick out any logged in initiators and drop all targets
# This will forcefully shut down TGTD even if there are active
# initiators logged in.
# Data in initiators write-cache not yet committed to the target
# will be lost.
# This will cause an unclean shutdown of the LUN.
forcedstop()
{
	echo "Forced shutdown of the iscsi target may cause data corruption
for initiators that are connected."
	echo "You have 30 seconds to press CTRL-C and abort this operation."
	sleep 30
	tgt-admin --delete ALL --force
	stop
}

restart()
{
	stop
	start
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	forcedstop)
		forcedstop
		;;
	restart)
		restart
		;;
	status)
		status tgtd
		RETVAL=$?
		;;
	condrestart)
		[ -f /var/lock/subsys/tgtd ] && restart
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|status|condrestart|forcedstop}"
		exit 1
esac
exit $RETVAL
