#!/bin/sh
#
# Name: hp_rescan
# Copyright: (c)2003 Hewlett-Packard Company
#
# Description
#
# Script performs a LUN rescan on one or all 
# QLogic adapters in the system
#
# Modification History
#
# Chad Dupuis	07/29/03 Initial Development
# Chad Dupuis   02/18/04 Changed multiplier for the times
#                        to wait for the QLogic adapter
#                        rescan to complete to 6
# Chad Dupuis   06/11/04 Changes for SLES 9 (2.6 kernel)

PROBELUNS="/opt/hp/hp_fibreutils/probe-luns"

# set the multiplier for the amount of seconds to wait
# for the QLogic adapter rescan to complete.  The amount
# of time to wait is number of adapters * multiplier

MULTIPLIER=6

# print usage statement

print_usage () {
 
 echo "hp_rescan: rescans LUNs on FC2214xx adapters"
 echo "Usage: hp_rescan -a|-i|-l"
 echo ""
 echo "-a: rescan all adapters"
 echo "-i: rescan a specific adapter instance"
 echo "-l: lists all FC2214xx adapters in system"
}


# list all FC2214xx adapters on system

list_adapters () {
 ARG=$1
 ADAPTLIST=""

 for i in $DIRLIST
 do
	if [ -d $i ]
	then
		cd $i
  		INSTLIST=`ls $i 2>/dev/null | grep \[0-9]`

		for j in $INSTLIST
  		do
   			ADAPTLIST=$ADAPTLIST" "$i/$j
			if [ "$ARG" = "print" ]
			then
				echo "$i/$j"
			fi
		done
 	fi
 done
}


# rescan all adapters on system

rescan_all () {
 list_adapters # produce list of adapters on system

 for i in $ADAPTLIST
 do
 	echo "Rescanning $i..."
 	echo "scsi-qlascan" > $i
 done

 NUMOFADAPTERS=`echo $ADAPTLIST | wc -l`
 SEC=`expr $NUMOFADAPTERS \* $MULTIPLIER`

 sleep $SEC # insert wait to allow rescans to be queued and
            # executed

 $PROBELUNS -a 
}


# rescan a particular adapter instance

rescan_inst () {
 ARG=$1

 FILENAME=`find /proc/scsi -name $ARG -print`

 # if the instance number doesn't exist, just return here

 if [ "$FILENAME" = "" ]
 then
	return
 fi

 echo "Rescanning $FILENAME..."
 echo "scsi-qlascan" > $FILENAME
 sleep 5 # wait for command to be queued and execute
 $PROBELUNS -i $ARG
}


# defines

PROBELUN=/opt/hp/hp_fibreutils/probe-luns
DIRLIST="/proc/scsi/qla2200 /proc/scsi/qla2300 /proc/scsi/qla2xxx"

# check number of arguments

if [ $# -lt 1 ]
then
 print_usage
 exit 1
fi

# set default values for output flags

AFLAG=0
IFLAG=0
LFLAG=0

# parse command line into arguments

getopt lai: $* 1>/dev/null 2>/dev/null

# check result of parsing

if [ $? != 0 ]
then
 echo "Bad argument or missing argument"
 exit 1
fi

set -- `getopt lai: $*`

while [ $1 != -- ]
do
 case $1 in
 	-l) LFLAG=1;;
	-a) AFLAG=1;;
	-i) IFLAG=1
	    INSTNUM=$2
            shift;;
 esac
 shift   # next flag
done

shift   # skip --

# parse argument that is passed in

if [ $LFLAG -eq 1 ]
then
 list_adapters print
 exit 0
elif [ $AFLAG -eq 1 ]
then
 rescan_all
 exit 0
elif [ $IFLAG ]
then
 rescan_inst $INSTNUM
else
 echo "Invalid argument"
 exit 1
fi



