#!/bin/sh
# Copyright (C) 2009 Draytek
# This script will be executed from dray_fwup to check WAN status
# echo 1: arp/ping detect success... WAN status is ok
# echo 0: arp/ping detect failed...WAN status may down.

	TMP_FILE=/tmp/ping_time
	TMP_SENT=/tmp/ping_sent
	uptime=$(cat /proc/uptime | awk 'FS="[.]+" {print $1}')
	Mode=$(uci -q get network.wan.detect || echo "0")	# 0:arp; 1:ping; 2:disabled
	
	[ "$Mode" == "2" -o $uptime -le 120 ] && {
		echo "2"
		exit
	}
	wanup=$(uci -P /var/state/ -q get network.wan.up || echo "0")
	if [ "$Mode" -ne "0" -a "$Mode" -ne "1" ]; then	# no arp or ping detection
		echo "$wanup"
		return
	fi

check_time() {
	RECURSIVE=1
	Idle=$(uci -q get network.wan.det_idle || echo "")	# the idle time
	Idle="${Idle:-15}"
	if [ "$1" -ne $RECURSIVE -a -e $TMP_SENT ]; then
		sent_time=$(cat $TMP_SENT || echo $uptime)
		sent_time="${sent_time:-$uptime}"
		INTV=$(($uptime - $sent_time))
		if [ $INTV -ge $Idle ]; then	## delay too long from last detection; CPU busy? 
			logger "[WAN] Stop WAN detection checking, busy?"
			echo 2
			return
		fi
	fi
	if [ -e $TMP_FILE ]; then
		wan_uptime=$(uci -P /var/state/ -q get network.wan.uptime | awk 'FS="[.]+" {print $1}')
		wan_uptime="${wan_uptime:-0}"
		pingtime=$(cat $TMP_FILE | awk 'FS="[.]+" {print $1}')
		pingtime="${pingtime:-$uptime}"
		DIFF=$(($uptime - $pingtime))
		DIFF1=$(($uptime - $wan_uptime))
		if [ $DIFF -ge $Idle -a $DIFF1 -ge $Idle ]; then
			if [ "$1" -ne $RECURSIVE ]; then 
				send_arping		# one more chance
				sleep 1
				check_time $RECURSIVE	# call myself to check again
				return
			fi			
			echo 0
		else
			echo 1
		fi
	else
		echo "0" > $TMP_FILE
	fi
}

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

send_arping() {
	#if enable ping detect
	uptime2file $TMP_SENT
	[ "$Mode" == "1" ] && {
		Host=$(uci -q get network.wan.pingip || echo "")
		[ -n "$Host" ] && {
			ping -c 1 -W 2 "$Host" >/dev/null && uptime2file $TMP_FILE &
		}
	} || 
	{
		# do arp detect
		local wantype=$(uci -q get network.wan.proto)
		if [ "$wantype" = "static" ] ; then
			local gateway=$(uci -q get network.wan.gateway)
			arping -f -c 2 -w 2 -I br-wan "$gateway" | grep -q "reply from $gateway" && uptime2file $TMP_FILE &
		elif [ "$wantype" = "pppoe" ] ; then
			[ "$wanup" == "1" ] && uptime2file $TMP_FILE &
		elif [ "$wantype" = "dhcp" ] ; then
			local gateway=$(uci -q -P /var/state get network.wan.gateway)
			if [ -n "$gateway" ]; then
				arping -f -c 2 -w 2 -I br-wan "$gateway" | grep -q "reply from $gateway" && uptime2file $TMP_FILE &
			else
				[ "$wanup" == "1" ] && uptime2file $TMP_FILE &
			fi
		else
			[ "$wanup" == "1" ] && uptime2file $TMP_FILE &
		fi
	}
}

	check_time
	send_arping