#!/bin/bash

if [ $# = 0 ]; then
 echo ""
 echo "Usage: ./lsbsd.sh <sas2|sas3> <device_name>"
 echo ""
 exit
fi

if [ $1 = "sas2" ] || [ $1 = "sas3" ]; then
 echo ""
else
 echo ""
 echo "Usage: ./lsihba.sh <sas2|sas3>"
 echo ""
 exit
fi


# define sasircu command depnding on the card in the system (sas2 or sas3)
sasgen="$1"ircu
# Ask for device if not goiven at runtime
dev=$2
if [ -z $2 ];then
	read -p "Which device are you looking for? " dev
fi

cardlist=$($sasgen list | awk '{print $1}' | grep '[0-9]' | grep -v SAS)
devlist=$(camcontrol devlist | awk ' { print $NF } ' | grep -w $dev | cut -f 2 -d , | sed 's/)//'g | grep -v pass)
if [ $? -ne 0 ];then
	echo "$dev is not present in system"
	exit
fi

## DISPLAY DEV AND SERIAL located with camcontrol
for device in $devlist; do 
	devserial=$(camcontrol identify $device | grep serial | awk '{print $NF}' | cut -f 2 -d -)
done

# Create file with slot # and corresponding serial number created from sasXircu
for card in $cardlist; do
	i=1
	for slot in $($sasgen $card display | grep 'Slot #' | awk -F: {'print $2'})
	do
		serial=$($sasgen $card display | grep 'Serial No' | awk -F: -v i=$i 'NR==i{print $2}' | xargs echo)
		printf "%s,%s,%s \n" "$card" "$slot" "$serial" >> /tmp/slots.txt
		let i=i+1 > /dev/null
    done
done

# Compare serial of device ($devserial) to the list created. Spit out corresponding slot number and card number.
c=$(cat /tmp/slots.txt | grep $devserial | cut -f1 -d ,)
s=$(cat /tmp/slots.txt | grep $devserial | cut -f2 -d ,)
SERIAL=$(cat /tmp/slots.txt | grep $devserial | cut -f3 -d ,)
CARD=$(expr $c + 1)
SLOT=$(expr $s + 1)
echo $CARD-$SLOT:$SERIAL
rm -f /tmp/slots.txt