#!/bin/sh
#
# check process to be started
#
# $Id: check_process.sh,v 1.6 2007-08-22 14:58:26 andozer Exp $
#
me=${0##*check_}	# strip path
me=${me%.*}	# strip extension
BASE=$HOME/agents
CONF=$BASE/etc/$me.conf
#WATCH_POINTS="2 7 32 37"
WATCH_TARGETS="$me"
PATH=/bin:/sbin:/usr/bin:/usr/sbin
TSTAMP=`date '+%s'`
WARNING=1
CRITICAL=2
UNKNOWN=3
RESULT=$CRITICAL
PASSIVE=1

EXT=0
MESS="Ok"

case `uname` in
 FreeBSD)	HOST=${HOST:-`hostname`} ;;
 Linux)		HOST=${HOST:-`hostname -f`} ;;
esac

Netsaint () {
	case "$PASSIVE" in
	[Yy][Ee][Ss]|1)
		echo "PASSIVE-CHECK:$me;$1;$2"
		exit 0
		;;
	*)	echo "$2"
		exit $1
		;;
	esac
}

die() {
	STATUS=$1
	MESSAGE=$2
	if [ $STATUS -gt $EXT ]
	then
		EXT=$STATUS
		MESS="$MESSAGE"

	elif [ $STATUS -eq $EXT ]
	then
		MESS="$MESS $MESSAGE"
	fi
}

[ -s $CONF ] && . $CONF

watch_it () {
	WATCH_ME=$1

	WATCHEE=`ps auwwx | grep "$WATCH_ME" | grep -v 'grep\|check_'`
	[ "$WATCHEE" ] && {
		[ ${INSTANCES:-1} -gt 1 ] || { 
			die 0 OK
			return 
		}
		[ $INSTANCES -gt `echo "$WATCHEE" | wc -l` ] || { 
			die 0 Ok
			return 
		}
	}
	die $RESULT "$WATCH_ME"
}

StartWatch() {
	WATCH_PROC=$1
	# watch_it
	[ "$WATCH_POINTS" ] || watch_it $WATCH_PROC
	
	set -- $WATCH_POINTS
	
	now=`date +%M`
	
	while [ $# -gt 1 ]
	do
		[ $now -gt $1 -a $now -lt $2 ] && watch_it $WATCH_PROC
	
		shift 2
	done
}

for i in $WATCH_TARGETS
do
	StartWatch $i
done

[ $EXT -eq 2 ] && MESS="$MESS not in process list"
Netsaint $EXT "$MESS"
