#!/bin/bash
#
# chkconfig: 345 88 20
# after pstorage-fs (S56) and after shaman (S57)
#
# (c) 2013. Parallels IP Holdings GmbH. All rights reserved.

### BEGIN INIT INFO
# Provides: pstorage-iscsid
# Required-Start: $remote_fs
# Default-Start:  3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: start and stop HA cluster manager
# Description: shaman is the HA cluster manager.
### END INIT INFO

[ -f /etc/sysconfig/network ] || exit 0

# Source function library.
source /etc/init.d/functions
source /usr/libexec/pstorage-iscsi/iscsi_functions
source $ISCSI_ETC/config

log=/var/log/pstorage/iscsi.log
lockfile=/var/lock/subsys/pstorage-iscsid

pcs_iscsi_init_host >$log 2>&1

function for_each_target {
	local action=$1
	local retval=0
	[ ! -d $ISCSI_SHM ] && mkdir -p $ISCSI_SHM
	ls $ISCSI_ETC/targets 2>/dev/null| while read target
	do
	        ( flock -w 20 -x 100 || exit 10
			link="$ISCSI_ETC/targets/$target"
			[  -h "$link" ] && path=`/bin/readlink $link 2>/dev/null`
			pcs_iscsi_is_registered_local $target >/dev/null 2>&1
			if [ $? -eq 0 ] ; then
				($action $path $target) 100<&-
				[ $? -ne 0 ] && retval=1
			else
				[ $? -ne 1 ] && retval=$?
			fi
	        ) 100>"$ISCSI_SHM/.lock_$target"
	done
	return $retval
}

function print_status {
	local path="$1"
	local target="$2"
		
	addr=`cat $path/control/address`
	echo -n "Target $target ($addr) "
	if [ -f "$path/control/.running" ] ; then
		echo "running"
	else
		echo "stopped"
	fi

	return 0
}

function iscsi_status {
	if [ -z "$ISCSI_ROOT" -o "x$(ls $ISCSI_ETC/targets)" = "x" ] ; then
		echo "No registered ISCSI targets on this host"
		exit 0
	fi

	for_each_target print_status	
	exit 0	
}

function start_target() {
	local path="$1"
	local target="$2"
	echo "Starting target $target" >$log
	pcs_iscsi_up_target $target >$log 2>&1
	if [ $? -ne 0 ] ; then
		echo "Unable start target $target" >$log
		return 1
	fi
	echo "Target $target was started succesfully" >$log
	return 0
}

function iscsi_start() {
	[ -z "$ISCSI_ROOT" ] && exit 0
	for_each_target start_target
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch $lockfile
	return $RETVAL
}

function stop_target() {
	local path="$1"
	local target="$2"
	echo "Stopping target $target" >$log
	pcs_iscsi_down_target $target "" "force" >$log 2>&1
	if [ $? -ne 0 ] ; then
		echo "Unable stop target $target" >$log
		return 1
	fi
	return 0
}

function iscsi_stop() {
	[ -z "$ISCSI_ROOT" ] && exit 0

	for_each_target stop_target
	RETVAL=$?
	rm -f $lockfile
	return $RETVAL
}

# See how we were called.
case "$1" in
  start)
	iscsi_start
	;;
  stop)
	iscsi_stop
	;;
  status)
	iscsi_status
	;;
  reload)
	exit 3
	;;
  *)
	echo $"Usage: $0 {start|stop|status}"
	exit 2
esac
