#!/bin/bash

Down () { Ping "$1" "$2" && return 0 || return 1; }
Up   () { Ping "$1" "$2" && return 1 || return 0; }

Ping () {
	local dev="$1"
	local target="$2"
	local max_attempts=8
	local ping_attempt=0

	[ "$dev" -a "$target" ] && while [ $ping_attempt -lt $max_attempts ]
	do
		ping_attempt=`expr $ping_attempt + 1`
		if /bin/ping -n -q -c 1 -i 1 -w 8 -I ${dev} ${target} >/dev/null
		then
			[ "$VISUAL" ] && echo "ping $target on $1 ok."
			return 1
		fi
	done
	[ "$VISUAL" ] && echo "ping $target on $1 failed!"
	return 0
}

#
# MAIN
#

ARG_ORIG="$*"
while : 
do  
	for ARG in "$@"
	do
		case $ARG in 
			-v|--visual) VISUAL="yes"; shift ;;
			*) [ "$ARG_EXEC" ] && ARG_EXEC="$ARG_EXEC $1" || ARG_EXEC="$1"; shift ;;
		esac    
		continue 2
	done
	break
done

RHOST="208.220.171.7"	# rh.tzo.com - reliable remote hostname (my dynamic dns provider)
[ -f /etc/dhcpc/dhcpcd-eth1.info ] && eval `sed 's/^\(.*\)=\(.*\)$/CABLE_\1=\2/' /etc/dhcpc/dhcpcd-eth1.info`
ADSL_IPADDR="`/sbin/ip addr show dev ppp0|sed -ne 's/  *inet \([0-9][0-9\.]*\) .*$/\1/p'`"
ADSL_GATEWAY="`/sbin/ip addr show dev ppp0|sed -ne 's/.*  *peer \([0-9][0-9\.]*\).*\/[0-9][0-9]* .*$/\1/p'`"

[ "$VISUAL" ] && echo "checking interface gateways..."
if [ ! "$CABLE_GATEWAY" ] || Down eth1 "$CABLE_GATEWAY"; then /etc/rc.d/init.d/cable restart; sleep 5; fi
if [ ! "$ADSL_GATEWAY"  ] || Down ppp0 "$ADSL_GATEWAY" ; then /etc/rc.d/init.d/adsl  restart; sleep 5; fi

[ "$VISUAL" ] && echo "checking reliable host..."
if Down eth1 "$RHOST" && Up ppp0 "$RHOST"; then /etc/rc.d/init.d/cable restart; sleep 5; fi
if Down ppp0 "$RHOST" && Up eth1 "$RHOST"; then /etc/rc.d/init.d/adsl  restart; sleep 5; fi

