#!/bin/sh

#. /usr/local/bcnu/etc/bcnuenv
. $BCNUHOME/agent/agent_head

#set -x

param=$4
services=$5

bcnu_param

#set -x

host=$p1
severity=$p2
retries=$p3

SEVERITY=${severity:=$BCNUSEVERITY}
RETRIES=${retries:=$BCNURETRY}

while [ $RETRIES -ge 0 ]
	do

	if $PING $host $PINGPAR >$BCNUTMP/$host.$$ 2>&1
	   then
		BCNUAGENT="$SAVAGENT-ping"
		BCNUMSG="$BCNU -h $host -m 'ok - up and available' -e $BCNU_OK -t $BCNUHOSTTYPE $BCNUHOST"
		bcnu_send
		OK=1
		break
	else
		RETRIES=`expr $RETRIES - 1`
		if [ $RETRIES -le 0 ]
		then        
			BCNUAGENT="$SAVAGENT-ping"
			EMSG="(no connectivity)"
			if [ $SEVERITY -eq $BCNU_ERR ] 
			then
				BCNUMSG="$BCNU -h $host -m 'error - problem with network' -e $BCNU_ERR -t $BCNUHOSTTYPE $BCNUHOST"
				bcnu_err_send
			else
				BCNUMSG="$BCNU -h $host -m 'warning - problem with network' -e $BCNU_WARN -t $BCNUHOSTTYPE $BCNUHOST"
				bcnu_warn_send
			fi
			OK=0
		else
			sleep $BCNUSLEEP
			echo "$STAMP agent($BCNUAGENT): retry $host"
		fi
	fi
done
for param in $services
	do
		bcnu_param
#set -x
		SERVICE=$p1
		severity=$p2
		retries=$p3

		SEVERITY=${severity:=$BCNUSEVERITY}
		RETRIES=${retries:=$BCNURETRY}

		FILE=${p4:+"-f $p4"}

		BCNUAGENT=$SAVAGENT-$SERVICE
		if [ -z "$EMSG" ]
			then
				RETRIES=${retries:=$BCNURETRY}
			else
				RETRIES=0
		fi
		while [ $RETRIES -ge 0 ]
		do
			if $BCNU -a net -s $SERVICE $FILE $host >$BCNUTMP/$host-$SERVICE 2>&1
			then
				BCNUMSG="$BCNU -h $host -m 'ok - Service $SERVICE available' -f $BCNUTMP/$host-$SERVICE -e $BCNU_OK -t $BCNUHOSTTYPE $BCNUHOST"
				bcnu_send
				break
			else
				RETRIES=`expr $RETRIES - 1`
				sleep $BCNUSLEEP
				echo "$STAMP agent($BCNUAGENT): retry $host"
			fi
		done
		if [ $RETRIES -le 0 ]
			then
				if [ $SEVERITY -eq $BCNU_ERR ] 
				then
					BCNUMSG="$BCNU -h $host -m 'error - Service $SERVICE not responding $EMSG' -f $BCNUTMP/$host-$SERVICE -e $BCNU_ERR -t $BCNUHOSTTYPE $BCNUHOST"
					bcnu_err_send
				else
					BCNUMSG="$BCNU -h $host -m 'warning - Service $SERVICE not responding $EMSG' -f $BCNUTMP/$host-$SERVICE -e $BCNU_WARN -t $BCNUHOSTTYPE $BCNUHOST"
					bcnu_err_send
				fi
				OK=0
		fi

done

rm $BCNUTMP/$host.$$
