#!/bin/sh

# This script is used to setup a failover server to run network tests, 
# if the normal (primary) network test server fails.
#
# It queries the Hobbit server (the one collecting data and doing the
# webpages) for how long ago the "bbtest" status was updated. If that
# status is too old, then it creates the file $BBTMPE/primarynetDOWN
# to indicate that the primary network test server is down.
# If the status is recent, then it removes the file to indicate
# that the failover server should not run the network tests.
#
# The actual running of the network tests is done elsewhere, e.g.
# from a script that checks for the presence of $BBTMP/primarynetDOWN
# 
# Henrik Storner (C) 2007-11-02

HOBBITSERVER=$1; shift		# Name or IP of the Hobbit server
NETTESTSERVER=$1; shift		# Name of the primary network test server
MAXNETAGE=$1; shift		# Max age of the status, in seconds

if test "$NETTESTSERVER" = ""
then
	NETTESTSERVER=$HOBBITSERVER
fi

if test "$MAXNETAGE" = ""
then
	MAXNETAGE=420
fi

LASTNETCHECK=`$BB $HOBBITSERVER "hobbitdboard host=^${NETTESTSERVER}\$ test=^bbtest\$ fields=logtime"`
if test $? -ne 0
then
	echo "Hobbit server not available, aborting"
	exit 1
fi

NOW=`date +%s`
NETCHECKAGE=`expr $NOW - $LASTNETCHECK`
if test $NETCHECKAGE -le $MAXNETAGE
then
	rm $BBTMP/primarynetDOWN

	$BB $BBDISP "status $MACHINE.fo green `date` Primary UP
		Network tests on primary OK, last was $NETCHECKAGE seconds ago
		"
else
	echo $HOBBITSERVER >$BBTMP/primarynetDOWN

	$BB $BBDISP "status $MACHINE.fo red `date` Primary DOWN
		Network tests on primary STALLED, last was $NETCHECKAGE seconds ago
		"
fi

exit 0

