!/bin/sh
# check_backup_wan script
# ue0  is the 2nd WAN interface. igb0 is the primary WAN
# 1.1.1.1 is set as the monitor IP on the primary WAN interface
# The idea is to get the IP addresses of the primary and secondary WAN interfaces.
# If the primary WAN IP address is not available, assume the primary WAN is still down.
# Assuming the primary WAN is still up, check if there any live TCP connections on the backup WAN.
# If live TCP/UDP connections are found on the backup WAN, check that the primary WAN is responding to
# pings on the monitor IP address.  If the primary WAN is responding to pings, then kill the states
# on the backup WAN, and they will automatically reconnect over the primary WAN.

check_wan_time=`date "+%Y-%m-%d %H:%M:%S"`
check_wan='1.1.1.1'

wan_ipaddress=`ifconfig igb0 | grep 'inet ' | awk '{ print $2}' | cut -d'/' -f1`
wan2_ipaddress=`ifconfig ue0 | grep 'inet ' | awk '{ print $2}' | cut -d'/' -f1`
active_tcp_udp_sessions=$(pfctl -i ue0 -ss | grep 'tcp\|udp' | wc -l)

echo 'primary, backup WAN IP address ' ${wan_ipaddress} '(primary) ' ${wan2_ipaddress} '(backup)'
# check for valid primary WAN IP address.
if [ -z "${wan_ipaddress}" ]; then
  echo ${check_wan_time} '... primary WAN is still down (no WAN IP)' | tee -a /var/log/check_backup_wan.log
  exit 0
fi

# check for active connections on backup_wan
pfctl -i ue0 -ss | grep 'tcp\|udp'
wan2_liveconn=`pfctl -i ue0 -ss | grep 'tcp\|udp'`
if [ -n "${wan2_liveconn}" ]; then
# found active tcp/udp connection(s) on the backup wan interface
  ping -c 2 -t 2 -S ${wan_ipaddress} ${check_wan} > /dev/null 2>&1
  wan1_resp=$?
  wan_resp=`expr ${wan1_resp}`

  echo 'primary WAN ping check (0 means passed)' ${wan1_resp}

  if [ ${wan_resp} -eq 0 ]; then
    echo ${check_wan_time} 'Killing states and resetting connections on backup WAN. The total number of active TCP/UDP sessions on backup WAN are $active_tcp_udp_sessions and they have been disconnected as the primary WAN is now online.  The secondary WAN active sessions
are no longer required.' | tee -a /var/log/check_backup_wan.log
    echo -e "${check_wan_time} \n \n  The total number of active TCP/UDP sessions on backup WAN are $active_tcp_udp_sessions and they have been disconnected as the primary WAN is now online.  The secondary WAN active sessions are no longer required." | /usr/local/bin/mail.php -s"Cleared WAN2 Active Sessions"
    pfctl -k 192.168.1.118
  else
    echo ${check_wan_time} 'The primary WAN is still down (pings failing)' | tee -a /var/log/check_backup_wan.log
  fi
else
  echo ${check_wan_time} 'There are no active TCP or UDP connections found on backup WAN' | tee -a /var/log/check_backup_wan.log
fi

