#! /bin/bash
#
# Server_Check: Run a minute by minute check of the
#   Master server (127.162.203.209 with private address
#   of 10.1.1.44), trigger failover if
#   Master goes off-line, trigger backdown if
#   Master goes back on-line. 
#   Run via cron - every minute
#     * * * * *   /usr/local/sbin/Server_check
######
#
# The files are stored in /root/..
#
#   /root/config/ contains the network information
#     that is specific to this fail-over server
#     (the only information that is different
#     from the master) 
#
#   /root/master_backup/ contains the latest backup
#     image from the master server
#
# Check for existance of Trigger file
#   0 = Normal (Master is fine)
#   1 = Failover (This server has taken over)
#
if [ ! -f /root/config/trigger ]; then
    echo 0 > /root/config/trigger
fi

TRIGGER=`cat /root/config/trigger`

# Do a three pings in a minute.  If all three pings fail
#  j="xxx" and we fail the server over (if it's not
#  already in that state).
#  If one of the pings works then we assume that the
#  Master is up and we return to normal (if we are not
#  already in that state).
#
j=""; 
for i in 1 2 3 ;
   do 
   ping -qc1 10.1.1.44 >/dev/null || j="x"$j; 
   sleep 10; 
done; 

if [ "xxx" = "$j" ]; then 
  if [ ! "1" = "$TRIGGER" ]; then
    /usr/local/sbin/Server_Failover
    echo 1 > /root/config/trigger
    echo "Primary Squid server has failed - Secondary taking over" |mail -s "ALERT: Primary Squid server is down" root
  fi
else
  if [ "1" = "$TRIGGER" ]; then
    /usr/local/sbin/Server_Return
   echo 0 > /root/config/trigger
  fi
fi
