#!/bin/bash
# GWMover:  WAN/Gateway failover
# 	Pings gateway and switches to backup line when it goes down.
# 	Reverts to primary line when gateway becomes accessible.
# Modified version of script found at:
# http://www.howtoforge.com/forums/showthread.php?p=55402#post55402
#
# Last modified:  August 2, 2007
# Ameir Abdeldayem

PRIMARYPUB="66.92.162.1"
PRIMARYGW="10.0.5.1"
SECONDARYGW="10.0.0.1"

EMAILS="email@ddress1 email@ddress2"

function is_host_alive() # Returns success or failure as boolean
{
	PACKETS=3
	TRIES=5
	IP=$1 # saving contents in $1 before is used
	echo "Pinging $IP"
	i=0
	while [ $i -lt $TRIES ]; do
		REQUEST=$(ping -qc $PACKETS $IP |grep packets| cut -d" " -f1,4)
		set -- $REQUEST
		echo -e "Try $i: $1 $2 \t"
		if [ $1 != $2 ]; then
			echo "Bad news. $1 sent, $2 received."
			# exit
			exitcode=1
		else
			echo "Great! $1 sent, $2 received."
			exitcode=0
		fi
		i=$(expr $i + 1)
	done
	return $exitcode
}

CURRENTGW=`route | grep "default" | awk '{print $2}'`
function changegateway()
{

	if [ $1 != $CURRENTGW ]; then
		echo ".  We need to change the default route. After: $1 Before: $2"
		route add default gw $1
		route del default gw $2
		echo "The routing table has been changed!"
		route # view current routing table
		echo -e "$4 \n\nHere is the updated routing table:\n$(route)" | mutt -s "$3 ($(hostname))" $EMAILS
	else
		echo ", and we are already pointing to it."
	fi

}


function test()
{
	echo $1 $EMAILS
}

##################
# main starts here
##################

if is_host_alive $PRIMARYPUB ; then
	echo -n "The primary gateway is alive"
	SUBJECT="$PRIMARYPUB IS NOW UP"; BODY="The server $PRIMARYPUB is now up and was pinged via the current gateway of $CURRENTGW."
	changegateway $PRIMARYGW $SECONDARYGW "$SUBJECT" "$BODY"
#	test $PRIMARYGW
else
	echo -n "The primary gateway is dead :-( We should be on the backup line"
	SUBJECT="$PRIMARYPUB IS DOWN"; BODY="The server $PRIMARYPUB could not be pinged via the current gateway of $CURRENTGW."
        changegateway $SECONDARYGW $PRIMARYGW "$SUBJECT" "$BODY"
fi

