#!/bin/bash

case $DEBUG in
  1) set -x
     ;;
  *)
     ;;
esac

usage() {
	echo "smonitor : host, service and network monitoring program."
	echo "usage : smtpmonitor [ -h for help ] -f <smonitor.cfg>"
	echo 
	echo "config file syntax :"
	echo "host device_number max_percentage_allowed"
	echo "To find device numbers, do a"
	echo "snmpwalk -v2c  -c public <host> .iso.org.dod.internet.mgmt.mib-2.host.hrStorage.hrStorageTable.hrStorageEntry.hrStorageDescr"
	echo "or scli -c 'show system storage' <host>"
	echo 
	echo "This script is designed for crontab : it generates output only if one of max_percentages is reached."
}

while true ; do
  case $1 in
    -d) debug=1 ; set -x ; shift 1 ;;
    -h) usage ; exit 0 ;;
	-f) conffile=$2 ; shift 2 ;;
     *) break ;;
  esac
done

if [ -z "$conffile" ] ;	then
	usage
	exit 1
fi

hdmib=".iso.org.dod.internet.mgmt.mib-2.host.hrStorage.hrStorageTable.hrStorageEntry"
psmib=".iso.org.dod.internet.private.enterprises.ucdavis.prTable.prEntry.prErrMessage"

command='snmpget -v2c -Cf -Oqv -c public ${host} ${hdmib}.${item}.${device} | grep -v "No Such Object available"'

sed -e 's/#.*$//g' -e '/^[[:space:]]*$/d' -e 's/[[:space:]]+/ /g' $conffile | \
	while read host device maxpercentage ; do
		if [ $device = "proc" ] ; then
			snmpwalk -v2c -Oq -c public ${host} ${psmib} \
				| cut -d' ' -f2- \
				| sed -e '/^[[:space:]]*$/d' -e 's/^/'${host}' : /g'
		else
			size=`item=hrStorageSize eval ${command}`
			used=`item=hrStorageUsed eval ${command}`
			
			if [ -z "$size" -o -z "$used" ]
			then
				echo "${devicename}@${host} : no response from host"
			else
				percentageused=$((100*${used}/${size}))
				if [ ${percentageused} -ge ${maxpercentage} ] ; then 
					devicename=`item=hrStorageDescr eval ${command}`
					blocksize=`item=hrStorageAllocationUnits eval ${command}|cut -d' ' -f1`
					free=$(((${size}-${used})*${blocksize}/1024/1024))
					sizem=$((${size}*${blocksize}/1024/1024))
					echo "${devicename}@${host} : ${percentageused}% used (${free}M free / ${sizem}M total)"
				fi
			fi
		fi
done

