#!/bin/sh
# This script starts up a tunneling virtual server for httpd
# and then monitors all the known real servers removing
# and returning them as needed.
# 
# Only outside resource required is GNU wget.

cd `dirname $0`
SRCDIR=`pwd`

#
# Define variables
#

# Virtual Server variables
DIRECTOR=198.4.126.55
TCP_PORT=80
SERVERS="198.4.126.52 198.4.126.53"
LB=wlc

# General variables
SLEEPTIME=15
TMP=/tmp/mon.$$
DOWNHOSTS=$TMP/down
RETURN=0


function httpdPing()
{
    _HTTPDPING_IP=$1

    cd $TMP
    rm -rf index.html
    wget -q -T 5 -t 1 -nh http://$_HTTPDPING_IP
    if [ -f index.html ]; then
	true
    else
	false
    fi
}

function httpdState()
{
    _HS_IP=$1

    if [ -f $DOWNHOSTS/$_HS_IP ]; then
	false
    else
	true
    fi
}

function httpdChangeState()
{
    _HCS_IP=$1
    _HCS_STATE=$2

    if [ $2 = "up" ]; then
	/sbin/ipvsadm -a -t $DIRECTOR:$TCP_PORT -R $_HCS_IP -i
	rm -f $DOWNHOSTS/$_HCS_IP
	echo "$_HCS_IP now up."
    else
	/sbin/ipvsadm -d -t $DIRECTOR:$TCP_PORT -R $_HCS_IP
	date > $DOWNHOSTS/$_HCS_IP
	echo "$_HCS_IP now down."
    fi
}

mkdir -p $DOWNHOSTS

# Start up the DIRECTOR
/sbin/ifconfig eth0:0 $DIRECTOR netmask 255.255.255.255 broadcast $DIRECTOR up
/sbin/route add -host $DIRECTOR dev eth0:0
/sbin/ipvsadm -A -t $DIRECTOR:$TCP_PORT -s $LB

# Start by assuming all servers are up
for i in $SERVERS
do
    httpdChangeState $i up
done

# Now for the rest of time loop through the servers testing them
until [ 1 -ne 1 ]; do
    for i in $SERVERS
    do
	if ( httpdPing $i ) then
	    # httpd is up
	    if ( httpdState $i ) then
		true
	    else
		# httpd was down - back up!
		httpdChangeState $i up
	    fi
	else
	    # httpd is down
	    if ( httpdState $i ) then
		# httpd was up - has crashed!
		httpdChangeState $i down
	    else
		true
	    fi
        fi
    done
    sleep $SLEEPTIME
done

