#! /bin/bash
# Rescan scsi hosts for new LUNs

SCSI_HOST=/sys/class/scsi_host

print_usage()
{
	echo
        echo "Usage: iscsi-rescan  [-i host_id]"
        echo "-i : Rescan for new LUNs only on specific host ID"
}

is_num()
{
	case "$1" in
	-*[!0-9]*) rval=0;;
	*) rval=1;;
	esac
}

find_host_ids()
{
	i=0
	if [ $opt_i ]; then
		hosts=host$opt_i
		if [ ! -e $SCSI_HOST/$hosts ]; then
			echo "Host $opt_i does not exist"
			exit 1
		fi
	else
		hosts=`ls -1 $SCSI_HOST/`
	fi
	for host in $hosts; do
		host=$SCSI_HOST/$host
		proc_name=`cat $host/proc_name`
		if [ "$proc_name" = "iscsi-sfnet" ]; then
			host_no=${host:${#SCSI_HOST} + 5}
			host_ids[$i]=$host_no
			let "i += 1"
		elif [ $opt_i ]; then
			echo "Device is not an iSCSI device"
		fi
	done
}

# TODO: we should only rescan the devices that were here already
# new devices added from the host scan should already be up to date.
rescan_devices()
{
	for file in  `ls $SCSI_HOST/host${1}/device/target${1}:0:0`
	do
		if [ -e "$SCSI_HOST/host${1}/device/target${1}:0:0/$file/rescan" ]
		then
			echo 1 > $SCSI_HOST/host${1}/device/target${1}:0:0/$file/rescan
		fi
	done
}

while getopts i: opt; do
case $opt in
    i)
	if [ $OPTARG ]; then
		is_num $OPTARG
		if [ $rval -eq  1 ];then
			opt_i=$OPTARG
		else
			print_usage
			exit 1
		fi
	else
		print_usage
		exit 1
	fi;;
   ?)
	print_usage
	exit 1;;
esac
done

cat /proc/devices | grep -q iscsictl
if [ $? -ne 0 ]; then
	echo "###############################################################################"
	echo "iSCSI driver is not loaded"
	echo "###############################################################################"
	exit
fi

declare -a host_ids
find_host_ids
no_hosts=${#host_ids[*]}

i=0
while [ $i -lt $no_hosts ]; do
	if [ `cat $SCSI_HOST/host${host_ids[$i]}/session_established` -eq 1 ]; then
		echo "Rescanning host${host_ids[$i]} "
		rescan_devices ${host_ids[$i]}
		echo "0 0 -" > $SCSI_HOST/host${host_ids[$i]}/scan
	else
		echo "Skipping host${host_ids[$i]} - session not established"
	fi
	let "i += 1"
done
