#!/bin/sh

RELOAD=0
WAITING=0

NETCON=0
LASTSTATUS=""
CURSTATUS=""

SLEEP_TIME=30

test_connection() {
	local addr="$1"
	local defroute="$(ip r | grep default | awk '{print$3}' | head -1)"
	local def6route="$(ip -f inet6 r | grep default | awk '{print$3}')"
	local ping6dev="$(ip -f inet6 r | grep default | awk '{print$5}')"
	local resolvfile="$(uci -q get 'dhcp.@dnsmasq[0].resolvfile')"

	if [ -n "$addr" ]; then
		ping -q -w 5 -c 1 "$addr" >/dev/null 2>&1 && return 0
	elif [ -n "$defroute" ]; then
		ping -q -w 5 -c 1 "$defroute" >/dev/null 2>&1 && return 0
		if [ -e "$resolvfile" ]; then
			for nmsrv in $(grep nameserver "$resolvfile" | awk '{print$2}'); do
				ping -q -w 5 -c 1 "$nmsrv" >/dev/null 2>&1 && return 0
			done
		fi
	elif [ -n "$def6route" -a -n "$ping6dev" ]; then
		ndisc6 -w 5 -1 "$def6route" "$ping6dev" >/dev/null 2>&1 && return 0
	fi
	return 1
}

internet_test() {
	local dest

	# use the destination address given in config for connectivity check
	dest="$(uci -q get testnet.global.destination)"
	# for backwards compatibility
	[ -n "$dest" ] || dest="$(uci -q get 'system.@system[0].netping_addr')"

	test_connection "$dest"

	if [ "$?" -eq 0 ]; then
		NETCON=1
		echo "{ \"online\" : true }" > /tmp/internet_connection_status
	else
		NETCON=0
		echo "{ \"online\" : false }" > /tmp/internet_connection_status
	fi
}

connectivity_test() {
	internet_test

	if [ "$NETCON" -eq 1 ]; then
		CURSTATUS=1
		[ "$CURSTATUS" == "$LASTSTATUS" ] || ubus send internet '{"status" : "online"}'
		LASTSTATUS=1
	else
		CURSTATUS=0
		[ "$CURSTATUS" == "$LASTSTATUS" ] || ubus send internet '{"status" : "offline"}'
		LASTSTATUS=0
	fi
}

trap RELOAD=1 HUP

while true; do
	if [ "$WAITING" -eq 0 ]; then
		sleep "$SLEEP_TIME" &
		WAITING=1
	fi
	RELOAD=0
	connectivity_test
	[ "$RELOAD" -eq 0 ] && wait && WAITING=0
done
