#!/bin/sh
#
# /etc/init.d/tgtd
#
### BEGIN INIT INFO
# Provides:          tgtd
# Required-Start:    $remote_fs $network
# Should-Start:
# Required-Stop:     $remote_fs $network     
# Should-Stop:
# Default-Start:     3 5
# Default-Stop:      
# Short-Description: generic storage target daemon
# Description:       Starts and stops the generic storage target subsystem
### END INIT INFO

#
#
# pidfile: /var/run/tgtd.pid

TGTD_CONFIG=/etc/tgt/targets.conf

DAEMON=/usr/sbin/tgtd
PIDFILE=/var/run/tgtd.pid

# Source LSB init functions
. /etc/rc.status

rc_reset

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

case "$1" in
  start)
	echo -n "Starting SCSI target service: "
	modprobe crc32c
	modprobe scsi_tgt
	startproc $DAEMON
	# Put tgtd into "offline" state until all the targets are configured.
	# We don't want initiators to (re)connect and fail the connection
	# if it's not ready.
	tgtadm --op update --mode sys --name State -v offline
	# Configure the targets.
	tgt-admin -e -c $TGTD_CONFIG
	# Put tgtd into "ready" state.
	tgtadm --op update --mode sys --name State -v ready
	rc_status -v
        ;;
  stop)
	echo -n "Stopping target framework daemon:"
	# Remove all targets. It only removes targets which are not in use.
	tgt-admin --update ALL -c /dev/null &>/dev/null
	# tgtd will exit if all targets were removed
	tgtadm --op delete --mode system &>/dev/null
	RETVAL=$?
	if [ "$RETVAL" -eq 107 ] ; then
	    rc_failed 7
	elif [ "$RETVAL" -ne 0 ] ; then
	    echo -n "(still running)"
	    rc_failed
	else
	    killproc -TERM $DAEMON
	    rc_status
	    modprobe -r scsi_tgt 2>/dev/null || /bin/true
	    modprobe -r crc32c 2>/dev/null || /bin/true
	fi
	rc_status -v
        ;;
  reload)
	tgt-admin --update ALL -f -c $TGTD_CONFIG &>/dev/null
	rc_status -v
	;;
  restart)
	tgtadm --op update --mode sys --name State -v offline &>/dev/null
	RETVAL=$?
	if [ "$RETVAL" -eq 107 ] ; then
	    rc_failed 7
	    rc_status -v
	else
            $0 start
	fi
        ;;
  status)
	echo -n "Checking for SCSI target service"
	checkproc $DAEMON
	rc_status -v
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|status}"
        exit 1
esac
rc_exit
