#!/bin/sh

# checks average hrProcessorLoad via SNMP
# this is handy for checking overall CPU utilization

# the snmptable invocation may be UCD SNMP 4 specific in its options

# doesn't do performance data (thought it would be trivial to add)
# argument "parsing" is rudimentary

PATH=/bin:/usr/bin:/usr/local/bin
export PATH

myname=`basename "$0"`
OK=0
WARNING=1
CRITICAL=2
UNKNOWN=3

usage="usage: $myname host comm warn crit"

tmpout="/tmp/$myname.out.$$"
trap "rm -f $tmpout" EXIT
rm -f "$tmpout"


if [ "$#" -ne 4 ]; then
    echo "$myname: $usage"
    exit $UNKNOWN
fi

host="$1"; shift
comm="$1"; shift
warn="$1"; shift
crit="$1"; shift

snmptable -Cb -Cf '|' -CH -v 1 -c "$comm" "$host" \
    host.hrDevice.hrProcessorTable \
    > "$tmpout"

if [ ! -s "$tmpout" ]; then
    echo "$myname: no hrProcessorTable data received"
    exit $CRITICAL
fi

# Oh, now this is a hack - using awk exit code to provide average
msg=`awk < "$tmpout" '-F|' '
	{
	    total += $2;
	    printf " CPU%d: %d%%;", NR, $2;
	}
	END {
	    avg=total/NR;
	    printf " AVG: %d%%\n", avg;
	    exit avg;
	    }
	'`
avg=$?

# echo $msg
# echo $avg

if [ "$avg" -ge "$crit" ]; then
    code="$CRITICAL"
    str="CRITICAL CPU AVG $avg% >= $crit%"
elif [ "$avg" -ge "$warn" ]; then
    code="$WARNING"
    str="WARNING CPU AVG $avg% >= $warn%"
else
    code="$OK"
    str="OK CPU AVG $avg% < $warn%"
fi

echo "$str - $msg"
exit $code
