#!/bin/sh

# chkconfig: 2345 11 90
# description: Adjust default routes for adsl and cable links.

Routing_Table () {

	local action="$1"
	local pref="$2"
	local table="$3"
	local ipaddr="$4"
	local dev="$5"
	local gateway="$6"
	local metric="$2"

	if [ "`grep -E -l \"^[0-9]+ *	*${table}$\" /etc/iproute2/rt_tables`" ]
	then
		case "$action" in
			add)
				# replace the default metric provided by adsl/dhcp clients
				/sbin/ip route del default via ${gateway} metric 0 2>/dev/null
				/sbin/ip route replace default via ${gateway} metric ${metric}

				# remove the lookup and flush the table in case we execute this function again
				Routing_Table del "$pref" "$table" "$ipaddr"

				# add routing for LAN<->public interface communications.
				/sbin/ip rule add from ${ipaddr} lookup ${table} pref ${pref}
				/sbin/ip route replace default via ${gateway} dev ${dev} table ${table}
				;;
			del)
				case "${table}" in
					cable)	ipaddr="24\\.[0-9\\.]*" ;;
					adsl)	ipaddr="${ipaddr}" ;;
				esac

				/sbin/ip ru ls \
					| sed -n "s/\(${pref}\):	*\(from ${ipaddr} lookup ${table} \)$/\2 pref \1/p" \
					| while read lookup_record
				do
					/sbin/ip rule del $lookup_record
				done

				/sbin/ip route flush table ${table} 2>/dev/null
				;;
		esac
	fi
}

Custom_Routes () {
	echo "$CUSTOM_ROUTES" | while read ROUTE
	do
		ROUTE="`echo \"$ROUTE\"|sed 's/^\([^#]*\).*$/\1/'`"
		[ "$ROUTE" ] && /sbin/ip rule $1 $ROUTE 2>/dev/null
	done
}

[ -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'`"

CUSTOM_ROUTES="
	to 10.1.1.0/24     lookup main  pref 500	# LAN
	to 216.162.64.9    lookup adsl  pref 5000	# ns1.axess.com
	to 216.162.64.65   lookup adsl  pref 5000	# ns2.axess.com
	to 216.162.64.130  lookup adsl  pref 5000	# ns2.axess.com
	to 216.162.64.71   lookup adsl  pref 5000	# news.axess.com
	to 216.162.65.26   lookup adsl  pref 5000	# ns1.axess.com
	to 205.237.233.50  lookup cable pref 5000	# news.videotron.ca
	to 205.237.233.52  lookup cable pref 5000	# news.videotron.ca
"

case "$1" in 
	start)
		Custom_Routes add
		;;
	cable)
		[ "$CABLE_IPADDR" -a "$CABLE_GATEWAY" ] \
			&& Routing_Table add 1000 cable "$CABLE_IPADDR" eth1 "$CABLE_GATEWAY"
		;;
	adsl)
		[ "$ADSL_IPADDR" -a "$ADSL_GATEWAY" ] \
			&& Routing_Table add 2000 adsl "$ADSL_IPADDR" ppp0 "$ADSL_GATEWAY"
		;;
	stop)
		Custom_Routes del
		[ "$CABLE_IPADDR" ] && Routing_Table del 1000 cable "$CABLE_IPADDR"
		[ "$ADSL_IPADDR"  ] && Routing_Table del 2000 adsl  "$ADSL_IPADDR"
		;;
	restart)
		$0 stop
		$0 start
		$0 adsl
		$0 cable
		;;
esac

/sbin/ip route flush cache

