#!/bin/bash

MY_PATH=/usr/local/portalshaper
. $MY_PATH/settings

while [ 1 ]; do
                
	# Declare an array to hold the faulty interfaces
	declare -a ifdown

	for iface in "${IF_INTERNET[@]}"
	do
		# Check each interface in turn
		# FIXME: This ping will fail on any interface, if the default gateway interface
		# is down. This will result in all interfaces being restarted
		if ping -c1 -I $iface google.com > /dev/null || ping -c1 -I $iface simplelists.com > /dev/null; then
			# Connection okay
			echo all ok #> /dev/null
		else
			# Save to the array that this link is down
			ifdown=("${ifdown[@]}" $iface)
		fi
	done

	# Bring down the defective interface	
	for iface in "${ifdown[@]}"
	do
		echo Stopping $iface...
		ifdown $iface
	done

	if ((${#IF_INTERNET[@]} == ${#ifdown[@]}))
	then
		# If all interfaces are down, reload the ADSL module
		echo Removing solos_pci module...
		sleep 3
		rmmod solos_pci
		sleep 10
	fi
	
	for iface in "${ifdown[@]}"
	do
		echo Starting $iface...
		ifup $iface
	done

	if [ "${ifdown[*]}" != "${lastifdown[*]}" ]
	then
		if ((${#IF_INTERNET[@]} != ${#ifdown[@]}))
		then
			# If an interface has failed but there are still interfaces up then re-run
			# firewall for updated load balancing
			$MY_PATH/master
		fi
	fi

	lastifdown=${ifdown[*]}

	unset ifdown
	
	sleep 60
done
