#!/bin/sh

# check that the listed windows services are installed and active


# export MIBDIRS=/home/jsellens/mibs/microsoft-mibs:/usr/share/snmp/mibs
export MIBDIRS=/usr/local/nagios/share/mibs/microsoft-mibs:/usr/share/snmp/mibs
export MIBS=+LanMgr-Mib-II-MIB


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 svcname ..."

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


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

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

snmptable -Cb -Cf '|' -CH -v 1 -c "$comm" "$host" \
    enterprises.lanmanager.lanmgr-2.server.svSvcTable \
    | sed -e 's/"//g' \
    | sort --ignore-case > "$tmpout"

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

# if no args, just spit out the whole services list
# not much use, unless you're looking for a particular service
# and don't know its name so you want a list
if [ $# -eq 0 ]; then
    awk < "$tmpout" '-F|' '
	BEGIN { printf "OK: All Services: "; }
	{ printf "%s %s %s; ", $1, $2, $3; }
	END { printf "\n"; }
	'
    exit $OK
fi

# Now I could have dynamically written some fabulous awk script
# that does tha right thing for every argument.
# I'm too lazy, let's just loop through the args

code="$OK"
str="OK"
while [ $# -gt 0 ]; do
    res=`awk -v "name=$1" < "$tmpout" '-F|' '$1==name { print $2, $3; }'`
    case "$res" in
	installed\ active)
	    msg="${msg}$1 installed/active; "
	    ;;
	"")
	    msg="$1 not found; ${msg}"
	    code="$CRITICAL"
	    str="CRITICAL"
	    ;;
	*)
	    msg="$1 not installed/active: $res; ${msg}"
	    code="$CRITICAL"
	    str="CRITICAL"
	    ;;
    esac
    shift
done

echo "${str}: $msg"
exit $code
