#!/bin/sh
#FLIP1405 - Failover Server Solution
#RUN ON SECONDARY ASTERISK SERVER
#AUTHOR-GREGG HANSEN 20080208
#DEPENDENCIES: nmap, arping
#Find and Replace the following IPs with your IP scheme:
#192.168.1.200  = Virtual IP
#192.168.1.202  = Real IP Server 1

PRISTATUS=$(nmap -p 5060 -sU 192.168.1.202 | awk '{print $2}' | grep open)                     ###if Primary Asterisk up = 'open|filtered'
SECSTATUS=$(nmap -p 5060 -sU 127.0.0.1 | awk '{print $2}' | grep open)			    ###if Secondary Asterisk up = 'open|filtered'
PRIMARYIP=$(ifconfig eth0:1 | grep 192.168.1.200 | awk '{print $2}' | sed 's/addr://g')   ###if local owns Virtual = '192.168.1.200' 
VIRTUALIP=$(nmap -sP 192.168.1.200 | grep down | awk '{print $4}')                      ###if Virtual not pingable = 'down.'

if [ "$PRISTATUS" != "open|filtered" ] ; then   ###is primary asterisk down?
	if [ "$SECSTATUS" == "open|filtered" ] ; then     ###is secondary asterisk up?     
		if [ "$PRIMARYIP" != "192.168.1.200" ] ; then   ###does secondary not own virtual ip?
			if [ "$VIRTUALIP" == "down." ] ; then  ###is the virtual IP not pingable?
		       ifconfig eth0:1 192.168.1.200/24 up
			arping -U -c 5 -I eth0 192.168.1.200   ###Gratuitous ARP request
			fi
		fi
			
	else
		service asterisk start
	fi
else
	if [ "$SECSTATUS" == "open|filtered" ] ; then ###primary is up, is secondary up? (there can be only one!)
		service asterisk stop
	else
 			if [ "$PRIMARYIP" == "192.168.1.200" ] ; then ###primary is up, do we still have the virtual ip?
			ifconfig eth0:1 down
			fi
	fi
fi

