#!/bin/sh
# This script attempts to connect to configured targets

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

if [ ! -d $UNH_ISCSI_CONF ]
then
	exit 0
fi

# Set the Host number
export HOST="`/bin/basename /proc/scsi/iscsi_initiator/* 2>/dev/null`"

(( target_no = 0 ))

for ITARGET in ${UNH_ISCSI_CONF}/*
do
	[ "$ITARGET" = "fstab.iscsi" ] && continue
	[ ! -x $ITARGET ] && continue

	TARGET_ALIAS="`/bin/basename $ITARGET`"
	[ ! -z "$TARGET_ARG" -a "$TARGET_ARG" != "$TARGET_ALIAS" ] && continue
	
	(( tcount = tcount + 1 ))
	echo "Attempting to connect to ${TARGET_ALIAS}... "
	# Run the target file
	export TARGET_NO=$target_no

	/bin/sh $ITARGET

	if [ -d ${UNH_ISCSI_DEV}/${TARGET_NO} ]
	then
		(( 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}
	else
		(( ecount = ecount + 1 ))
	fi
done

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

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

# Some failed
exit 2
