#!/bin/bash

config=${1:-/etc/netgwm/netgwm.yml}

# backup gateway = the entry with priority: 2 in the gateways section
gwline=$(sed -n '/^[[:space:]]\+[^#].*: *{.*priority: *2[[:space:]]*[,}]/p' $config | head -1)
prov=$(sed -n 's/^[[:space:]]\+\([a-zA-Z0-9_-]*\):.*/\1/p' <<< "$gwline")

# source ip = the ip of the interface on the same subnet as the gateway
# (grep ip addr output for the first two octets of the gateway ip)
# for dev-based gateways, use the dev field directly
gwip=$(sed -n 's/.*ip: *\([0-9.]*\).*/\1/p' <<< "$gwline")
dev=$(sed -n 's/.*dev: *\([a-zA-Z0-9_-]*\).*/\1/p' <<< "$gwline")
if [ -n "$gwip" ]; then
	prefix=$(echo "$gwip" | cut -d. -f1-2)
	ip=$(ip -4 addr 2>/dev/null | grep -E "inet ${prefix}\." | sed -n 's/^[[:space:]]*inet \([0-9.]*\)\/.*/\1/p' | head -1)
else
	ip=$(ip -4 addr show dev "$dev" 2>/dev/null | sed -n 's/^[[:space:]]*inet \([0-9.]*\)\/.*/\1/p' | head -1)
fi

# fallback to built-in values if not found
prov=${prov:-interzet}
ip=${ip:-10.172.18.179}

if (ping -c 3 8.8.4.4 -I $ip > /dev/null); then
	sleep 0;
else
	echo "`hostname -f`: failover internet channel not working: $prov: $ip, date: `date +%Y-%m-%d\ %H:%M:%S`" |  mail -s "`hostname -f`: failover internet channel not working: $prov: $ip" root
fi
