#!/bin/sh
#
# targetcli	iSCSI target kernel configuration
#
# chkconfig:	345 70 20
# description:	iSCSI target kernel configuration
# config:	/etc/target/saveconfig.json

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

# Get network config
. /etc/sysconfig/network

# 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 targetcli
		exit 1
	fi
else
	exit 0
fi

start() {
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/targetcli ]; then
		msg_starting targetcli
		if /usr/bin/targetcli restoreconfig clear_existing=true > /dev/null ; then
			ok
			touch /var/lock/subsys/targetcli
			RETVAL=0
		else
			fail
			RETVAL=1
		fi
	else
		msg_already_running targetcli
	fi
}

stop() {
	if [ -f /var/lock/subsys/targetcli ]; then
		msg_stopping targetcli
		if /usr/bin/targetcli clearconfig confirm=true >/dev/null ; then
			ok
			rm -f /var/lock/subsys/targetcli > /dev/null 2>&1
			RETVAL=0
		else
			fail
			RETVAL=1
		fi
	else
		msg_not_running targetcli
	fi
}

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

reload() {
	if [ -f /var/lock/subsys/targetcli ]; then
		msg_reloading targetcli
		if /usr/bin/targetcli restoreconfig clear_existing=true >/dev/null ; then
			ok
			RETVAL=0
		else
			fail
			RETVAL=1
		fi
	else
		msg_not_running targetcli
		RETVAL=7
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  reload|force-reload)
	reload
	;;
  status)
	if [ -f /var/lock/subsys/targetcli ]; then
		nls "%s was started" "targetcli"
		echo "Sessions:"
		targetcli sessions
		RETVAL=0
	else
		nls "%s is stopped" "targetcli"
		RETVAL=3
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
esac
exit $RETVAL
