#!/bin/bash
# script that polls values from the brocade switches 
# var
critstatus=0
warnstatus=0
getval ()
{
oid=$1
/usr/bin/snmpget -c public -v 1 -O v $host  "$oid" | sed "s/.*INTEGER: \(.*\)$/\1/g"
}
getsens ()
{
sensor=$1
senstat=`getval FCMGMT-MIB::connUnitSensorMessage.'.....4..........'."$sensor"`
#type 1 is temp, type 2 is fan, type 3 is powersupply.
# determine type first
typ=`echo "$senstat" | sed 's/STRING: "sensor.*: type \([0-9]\) is \([A-Z]\+\), value is \([0-9]\+\|unknown\)"/\1/g'`
stat=`echo "$senstat" | sed 's/STRING: "sensor.*: type \([0-9]\) is \([A-Z]\+\), value is \([0-9]\+\|unknown\)"/\2/g'`
if [ "$typ" = 1 ] ; then
	value=`echo "$senstat" | sed 's/STRING: "sensor.*: type \([0-9]\) is \([A-Z]\+\), value is \([0-9]\+\|unknown\)"/\3/g'`
	if [ "$value" -le "$tempmax" ] && [ "$stat" = OK ] ; then
		tempstatus=0
	elif	[ "$value" -ge "$tempmax" ] && [ "$stat" = OK ] ; then
		warnstatus=1
		warnmsg="$warnmsg Temp$sensor $value"C
	else
		critmsg="$critmsg Temp$sensor $stat $value"C
		critstatus=2
	fi
elif [ "$typ" = 2 ] ; then
	value=`echo "$senstat" | sed 's/STRING: "sensor.*: type \([0-9]\) is \([A-Z]\+\), value is \([0-9]\+\|unknown\)"/\3/g'`
	if [ "$value" -ge "$rpmmin" ] && [ "$stat" = OK ] ; then
                fanstatus=0
	elif  [ "$value" -le "$rpmmin" ] && [ "$stat" = OK ] ; then
                warnstatus=1
                warnmsg="$warnmsg Fan$sensor $value"RPM
	else
                critmsg="$critmsg Fan$sensor $stat $value"RPM
		critstatus=2
        fi
elif [ "$typ" = 3 ] ; then
        if [ "$stat" = OK ] ; then
                psstatus=0
        else
                critmsg="$critmsg PowerSupply Fault"
                critstatus=2
        fi
fi
}
# get other snmp
getunitstat ()
{
unitstat=`getval .1.3.6.1.3.94.1.6.1.6.16.0.0.5.30.52.30.23.0.0.0.0.0.0.0.0`
if [ "$unitstat" = 3 ] ; then
        unitstatus=0
else
	critstatus=2
	critmsg="$critmsg Unit error:"
fi
}
# get ops
while getopts ":z:t:r:" opt; do
        case $opt in
        z)      host="$OPTARG" ;;
        t)      tempmax="$OPTARG" ;;
	r)	rpmmin="$OPTARG" ;;
	\?)     echo 'usage -z host -t max temp -r min rpm' ;;
        esac
done
shift $(($OPTIND -1))
# give some help
if [ -z "$host" ] ; then
	echo  'usage -z host -t max temp -r min rpm'
	exit 3
fi
# get unit status
getunitstat
# get sensors 1 to 10
getsens 1 ;getsens 2 ; getsens 3 ;getsens 4 ;getsens 5 ;getsens 6 ;getsens 7 ;getsens 8 ;getsens 9;getsens 10 
# compile results of tests
if [ "$critstatus" != 0 ] ; then
	echo "$critmsg"
	echo exit 2
	exit 2
fi
if [ "$warnstatus" != 0 ] ; then
        echo "$warnmsg"
	echo exit 1
        exit 1
fi
if [ "$critstatus" == 0 ] && [ "$unitstatus" == 0 ] &&  [ "$tempstatus" == 0 ] &&  [ "$fanstatus" == 0 ] &&  [ "$psstatus" == 0 ] ; then
	echo "Unit OK, temp ok, fans ok, ps ok"
	exit 0
fi
echo "Error checking device"
exit 3
