#!/bin/sh

. /lib/functions.sh

# uci_ lib works on temporary config files here which are not persistent
UCI_CONFIG_DIR=/var/run
CONFIG=plc-standby
STANDBY_TIMER=${1:-600}

SWITCHED_OFF=0

if [ -f /lib/ar71xx.sh ]; then
        PLATFORM=ar71xx
        . /lib/ar71xx.sh
elif [ -f /lib/ipq806x.sh ]; then
        PLATFORM=ipq806x
        . /lib/ipq806x.sh
fi
board=$(${PLATFORM}_board_name)

uptime_seconds() {
	(IFS="." read a b </proc/uptime; echo "$a")
}

restart_timer() {
	uci_set $CONFIG status timeout "$(( $(uptime_seconds) + $STANDBY_TIMER ))"
	uci_commit $CONFIG
}

get_wlan_devices() {
	uci_get $CONFIG status wlandevs
}

get_timer() {
	uci_get $CONFIG status timeout
}

# we are started with the plc, so restart standby timeout
restart_timer

while :; do
	SLEEP=30
	timeout=$(get_timer)
	devices=$(get_wlan_devices)
	if [ -z "$devices" ]; then
		debug "standby timeout expires at $timeout"

		swports=
		case "$board" in
		dlan-pro-1200-ac|\
		dlan-pro-1200-n)
			# for 1200+ WiFi ac: does port 3 or 4 have a link?
			swports="(3||4)"
			;;
		dlan-1000-ac)
			# for 1000 ac: does port 2 or 3 have a link?
			swports="(2||3)"
			;;
		dlan-550-wifi)
			# for 550: does port 2 have a link?
			swports="2"
			;;
		# TODO specify link detection for switchless devices supported
		*)
			# current default: never enter standby
			links=true
			;;
		esac
		if [ -n "$swports" ]; then
			# (jsonfilter not documented, but works similar to
			# http://goessner.net/articles/JsonPath/, or look at the jsonfilter grammar)
			# get all the link values of specified ports  with link=true, if not empty one eth port has a link
			links=$(ubus call network.swconfig status '{"switch":"switch0"}'|jsonfilter -l 1 -e '$.ports['"$swports"'&&@.link=true].link')
		fi
		if [ -n "$links" ]; then
			# restart timeout if ethernet ports are up
			debug "restart standby timer (eth)"
			restart_timer

			[ $SWITCHED_OFF = 1 ] && {
				[ -x /etc/init.d/plc ] && /etc/init.d/plc normal
				[ -x /etc/init.d/ghn ] && /etc/init.d/ghn normal
				SWITCHED_OFF=0
			}
		else
			# if down let the timer expire
			[ "$(uptime_seconds)" -ge "$timeout" ] && [ $SWITCHED_OFF = 0 ] && {
				# enter plc standby if timed out
				debug "standby timer expired"

				[ -x /etc/init.d/plc ] && /etc/init.d/plc standby
				[ -x /etc/init.d/ghn ] && /etc/init.d/ghn standby
				SWITCHED_OFF=1
			}

			# if timeout active check every few seconds if ports went up again
			SLEEP=5
		fi
	else
		debug "restart standby timer (wifi)"
		restart_timer
		[ $SWITCHED_OFF = 1 ] && {
			[ -x /etc/init.d/plc ] && /etc/init.d/plc normal
			[ -x /etc/init.d/ghn ] && /etc/init.d/ghn normal
			SWITCHED_OFF=0
		}
	fi
	sleep $SLEEP
done