#!/bin/bash
#
# Name: lssg
# Copyright: (C) 2003 Hewlett-Packard Company
#
# Description: lists all sg devies and a description
#              of each device
#
# Modification History
#
# Chad Dupuis	08/26/04 Initial Development

# functions

space_str () {
 STRINGSIZE=$1
 STR=$2 
 SPACESTR=""
 
 SIZE=`echo $STR | wc -c`
 NUM_OF_SPACES=`expr $STRINGSIZE - $SIZE`

 COUNT=$NUM_OF_SPACES

 while [ $COUNT -ne 0 ]
 do
  SPACESTR=$SPACESTR" "
  COUNT=`expr $COUNT - 1`
 done
}
 
# defines

SCSI_INFO="/opt/hp/hp_fibreutils/scsi_info"

# check to make sure that scsi_info exists

ls $SCSI_INFO 1>/dev/null 2>/dev/null

if [ $? -ne 0 ]
then
 echo "$SCSI_INFO does not exist"
 exit 1
fi

DONE=0
i=0

while [ $DONE -eq 0 ]
do
 # check to see if device is bound 

 $SCSI_INFO /dev/sg${i} 1>/dev/null 2>/dev/null

 if [ $? -ne 0 ]
 then
 	DONE=1
 fi

 if [ $DONE -eq 0 ]
 then
 	# get device info from scsi_info

 	OUTPUT=`$SCSI_INFO /dev/sg${i}` 
 	CONN=`echo $OUTPUT | awk 'BEGIN {FS=":"} {print $1}' | awk 'BEGIN {FS="="} {print $2}' | sed 's/"//g'`
 	VENDOR=`echo $OUTPUT | awk 'BEGIN {FS=":"} {print $2}' | awk 'BEGIN {FS="="} {print $2}' | sed 's/"//g'`
 	MODEL=`echo $OUTPUT | awk 'BEGIN {FS=":"} {print $3}' | awk 'BEGIN {FS="="} {print $2}' | sed 's/"//g'`
 	FWREV=`echo $OUTPUT | awk 'BEGIN {FS=":"} {print $4}' | awk 'BEGIN {FS="="} {print $2}' | sed 's/"//g'`
 
 	# get the number of spaces to pad after the connection address

 	space_str 6 "sg${i}"
 	DEVICESPACE=$SPACESTR 
 	space_str 16 $CONN
 	CONNSPACE=$SPACESTR

 	# get wwid for sg devices

 	WWID=""
 	ADAPTERINST=`echo $CONN | awk 'BEGIN {FS=","} {print $1}'`
 	INSTFILE=`find /proc/scsi/qla* -name "$ADAPTERINST" -print 2>/dev/null`

 	if [ "$INSTFILE" != "" ]
 	then
 		DEVICETARGET=`echo $CONN | awk 'BEGIN {FS=","} {print $3}'`
		WWID=`cat $INSTFILE | grep target | grep "\-${DEVICETARGET}=" | awk 'BEGIN {FS="="} {print $2}' | sed 's/;//'`
 	fi
 
 	# format world wide ID string

 	if [ "$WWID" != "" ]
 	then
  		WWID="`echo $WWID | cut -c 1-4`"-"`echo $WWID | cut -c 5-8`"-"`echo $WWID | cut -c 9-12`"-"`echo $WWID | cut -c 13-16`"
 	fi 
 
 	echo "sg${i}${DEVICESPACE} ${CONN}${CONNSPACE} $VENDOR $MODEL $FWREV  $WWID"
 	
	# increment counter

	i=`expr $i + 1`
 fi
done
