#! /bin/sh

iscsitarget=$1
lun_number=$2

iscsi_session_dir="/sys/class/iscsi_session"
disk=""

scsi_hosts=`cat /proc/scsi/scsi | grep "Host:" | sed 's/ /_/g'`

for scsi_host in $scsi_hosts
do
	scsi_host=`echo $scsi_host | sed 's/_/ /g'`
	hostid=`echo $scsi_host | awk '{print $2}' | sed 's/scsi//'`

	channel=`echo $scsi_host | awk '{print $4}'`
	channel=`expr $channel + 0`
	
	id=`echo $scsi_host | awk '{print $6}'`
	id=`expr $id + 0`

	lun=`echo $scsi_host | awk '{print $8}'`
	lun=`expr $lun + 0`

	if [ $lun -ne $lun_number ]
	then
# This is not the Lun we are looking for.
		continue;
	fi
	
	found=0
	for session in `ls $iscsi_session_dir`
	do
		if [ -d $iscsi_session_dir/$session/device/target$hostid:$channel:$id ];then
			found=1
			break;
		fi
	done
	if [ $found -eq 0 ];then
		continue;
	fi

	tgname=`cat $iscsi_session_dir/$session/targetname`
	if [ "$iscsitarget" == "$tgname" ]; then
		blockdev=`ls -d $iscsi_session_dir/$session/device/target$hostid:$channel:$id/$hostid:$channel:$id:$lun/block*`
		if [ $? -ne 0 ]
		then
			# why am I here? We should have found a device
			# by now. Something very serious has happened.
			# We may have lost the iscsi connection just 
			# before we could see the device.
			echo "Error: Failed to detect Disk. Exiting..."
			exit 1
		fi
		disk=/dev/`basename $blockdev | cut -d ":" -f2`
		if [ "$disk" == "/dev/" ]
		then
			echo "Error: Failed to detect Disk. Exiting..."
			exit 1
		fi
		break;
	fi
done
if [ -z "$disk" ]
then
	echo "Error: No disk found"
	exit 1
fi
echo $disk
