#!/bin/bash 

# This script periodically pings my DNS server. If there
# is no response then the power to my modem is cycled.
# The modem's power is controlled by the relay on the ADU100. 
# Cycling the power causes the modem to reconnect.
# NOTE: the adutux driver must be installed.
# NOTE: the adu command line utility must be installed.
# NOTE: This script does not address the cause of my connection
#       problems. It is a work-a-round until I can get the
#       issue sorted. UPDATE: My problem was an excess of
#       BitTorrent connections that overflowed the NAT table
#       in my modem.
# NOTE: relay 0 on my ADU device is spliced into the low voltage
#       power supply wire of my modem

echo "++++ checklink.sh started monitoring at `date` " >> linklog.txt

exit_handler(){
echo "---- checklink.sh stopped at `date` " 1>>linklog.txt
exit 1
}

trap exit_handler 0 1 2 3 5 10 13 15

# issue a "set relay 0" command to the ADU100
/usr/bin/adu -i 0 sk0 2>>linklog.txt

# sleep to let the system initialize at startup
sleep 5m

while [ TRUE ] 
do
# -ping the DNS server of my ISP (replace the xxx values with your own)
# -feel free to improve this code to use your resolv.conf or a
# dynamic DNS address (or any other IP address that works for you)
# -checks two IP addresses to avoid a false positive if one server 
# is down
	pingtest1=`ping -c 1 xxx.xxx.xxx.xxx | grep '1 received'`
	pingtest2=`ping -c 1 xxx.xxx.xxx.xxx | grep '1 received'`

	if [ ${#pingtest1} -eq 0 ]
	then
		if [ ${#pingtest2} -eq 0 ]
		then
			echo "connection dropped `date`" 1>>linklog.txt
			# play the alarm message (pick a method that works on your system)
			###/usr/bin/aplay -D plug:dmix /usr/lib/python2.3/test/audiotest.au & 
			/usr/bin/beep &
			### cat /usr/lib/python2.3/test/audiotest.au > /dev/audio
			# issue a "reset relay 0" command to the ADU100
			/usr/bin/adu -i 0 rk0 2>>linklog.txt
			# 10 seconds of power loss is adequate to reset my modem
			sleep 10
			# issue a "set relay 0" command to the ADU100
			/usr/bin/adu -i 0 sk0 2>>linklog.txt

			# I sleep for 5 minutes since it takes several MINUTES 
			# for my connection to come back up.
			sleep 5m
		fi
	fi
	sleep 1m
done

