#!/bin/sh

wan_disable=$(uci -q get network.wan.disable 2>/dev/null || echo 0)
voipwan_disable=$(uci -q get network.voipwan.disable 2>/dev/null || echo 1)
iptvwan_disable=$(uci -q get network.iptvwan.disable 2>/dev/null || echo 1)
if [ "$wan_disable" == "1" -a "$voipwan_disable" == "1" -a "$iptvwan_disable" == "1" ]; then
	exit 0;
fi

now=$(cat /proc/uptime | awk 'FS="[.]+" {print $1}')

[ "$wan_disable" == "1" ] || {
	runtime=$(uci -q -P /var/state get network.ifup_running 2>/dev/null)

	if [ $now -ge 100 -a -n "$runtime" ]; then
		DIFF=$(($now - $runtime))
		if [ $DIFF -le 30 ]; then
			logger "ifup is running.......skip check_pppwan"
			return
		fi
	fi
	#if ipv6 is running, do not reset WAN. 
	ipv6_mode=$(uci -q get ipv6.wan.mode)
	if [ "$ipv6_mode" = "link-local" ]; then
		#If WAN mode=3g, reset it with "3G" input.(every 300 sec)
		wan_mode=$(uci -q get network.wan.proto)
		if [ "$wan_mode" != "3g" -o "$1" = "3G" ]; then
			defroute=$(route -n | grep '^0.0.0.0' -c 2>/dev/null)
			if [ "$defroute" != "1" ]; then
				logger "[WAN] check default route failed:($defroute), revert WAN state and ifup wan..."
				uci -q -P /var/state revert network.wan
				/sbin/ifup wan
			fi
		fi
		
		if [ "$wan_mode" == "l2tp" -o "$wan_mode" == "pptp" ]; then
			deifc=$(route -n | grep '^0.0.0.0' | grep ppp -c 2>/dev/null)
			if [ "$defroute" == "1" -a "$deifc" != "1" ]; then
				logger "[WAN] check default route failed:($defroute), revert $wan_mode WAN state and ifup wan..."
				uci -q -P /var/state revert network.wan
				/sbin/ifup wan
			fi
		fi
	fi
}

[ "$voipwan_disable" == "1" ] || {
	voip_up=$(uci -q -P /var/state get network.voipwan.up 2>/dev/null || echo 0)
	[ "$voip_up" == "1" ] && exit 0
	DOWN_TIME=`uci -q -P /var/state get network.voip_down 2>/dev/null || uci -q -P /var/state set network.voip_down="$now"`
	DOWN_TIME="${DOWN_TIME:-$now}"
	DIFF=$(($now - $DOWN_TIME))
	if [ $DIFF -ge 30 ]; then
			logger "[WAN] Revert VoIP WAN state and start voip wan..."
			uci -q -P /var/state revert network.voip_down
			uci -q -P /var/state revert network.voipwan		# revert failed in ifdown ???
			/sbin/ifup voipwan
	fi
}

[ "$iptvwan_disable" == "1" ] || {
	iptv_up=$(uci -q -P /var/state get network.iptvwan.up 2>/dev/null || echo 0)
	[ "$iptv_up" == "1" ] && exit 0
	DOWN_TIME=`uci -q -P /var/state get network.iptv_down 2>/dev/null || uci -q -P /var/state set network.iptv_down="$now"`
	DOWN_TIME="${DOWN_TIME:-$now}"
	DIFF=$(($now - $DOWN_TIME))
	if [ $DIFF -ge 30 ]; then
			logger "[WAN] Revert VoIP WAN state and start iptv wan..."
			uci -q -P /var/state revert network.iptv_down
			uci -q -P /var/state revert network.iptvwan		# revert failed in ifdown ???
			/sbin/ifup iptvwan
	fi
}