#!/bin/sh
# This script attempts to disconnect from all connected targets

UNH_ISCSI_CONF=/etc/unh_iscsi_initiator
UNH_ISCSI_DEV=/dev
TARGET_ARG=$1
(( tcount = 0 ))
(( ecount = 0 ))

# Set the Host number
HOSTPATH="`ls /proc/scsi/iscsi_initiator/* | /bin/egrep -v "target|conn|stat" 2>/dev/null`"
export HOST="`/bin/basename $HOSTPATH`"

for ITARGET in ${UNH_ISCSI_DEV}/*
do
	if [ -L ${ITARGET} ] 
	then
		# This could be one of the links
		/bin/rm ${ITARGET}
		continue
	fi

	TARGET_NO="`/bin/basename ${ITARGET}`"
	(( tcount = tcount + 1 ))

	# Disconnect from target
	if [ -f $HOSTPATH ] ; then
		echo "Attempting to disconnect from ${ITARGET}... "
		iscsi_config down host=$HOST target=${TARGET_NO}
		else
			echo " No iSCSI HBA found: $HOSTPATH "
			(( ecount = ecount + 1 ))
	fi

	# The device file for the target should have gone away
	if [ -d ${UNH_ISCSI_DEV}/${TARGET_NO} ]
	then
		(( ecount = ecount + 1 ))
	else
		(( target_no = target_no + 1 ))

		# Erase any old instance
		/bin/rm -f ${UNH_ISCSI_DEV}/${TARGET_ALIAS} 2>/dev/null

		# Link the device name to target alias
		ln -s ${UNH_ISCSI_DEV}/${TARGET_NO} ${UNH_ISCSI_DEV}/${TARGET_ALIAS}
	fi
done

# All passed
[ $ecount -eq  0 ] && exit 0

# All failed
[ $ecount -eq  $tcount ] && exit 1

# Some failed
exit 2
