#!/bin/sh
# Copyright (C) 2008-2010 OpenWrt.org

. /usr/share/libubox/jshn.sh

eth_led_handler(){

[ -f "/tmp/firmwareupgrading" ] && return

proto="$(uci -c /etc/webui/config/ get ipv4.current.proto)"
protov6="$(uci -c /etc/webui/config/ get ipv6.current.IPv6_ConnectionType)"
MSG=$(ubus call network.device status '{"name":"eth1"}')
MSG3=$(ifconfig | grep eth1)
if [ "$proto" == "dynamic_pptp" -o "$proto" == "static_pptp" -o "$proto" == "dynamic_l2tp" -o "$proto" == "static_l2tp" ]
then
	MSG2=$(ubus call network.interface.vpn status)
else
	if [ "$proto" == "dslite" ]
	then
		if [ "$protov6" == "IPv6_PPPoE" ]
		then
			pppoetype="$(uci -c /etc/webui/config/ get ipv6.pppoe.IPv6_PppoeType)"
			if [ "$pppoetype" == "Dynamic" ]
			then
				MSG2=$(ubus call network.interface.wan6_6_4 status)
			else
				MSG2=$(ubus call network.interface.wan6_4 status)
			fi
		else
			if [ "$protov6" == "IPv6_AutoConfiguration" ]
			then
				MSG2=$(ubus call network.interface.wan6_4 status)
			else
				MSG2=$(ubus call network.interface.wan status)
			fi
		fi
	else
		MSG2=$(ubus call network.interface.wan status)
	fi
fi

json_init

json_load "$MSG"

if json_get_var carrier carrier && [ "$carrier" == "1" ]
then
		json_load "$MSG2"
		if json_get_type Type ipv4-address && [ "$Type" == array ]
		then
			ledctrl eth orange off
			ledctrl eth white on
		else
			ledctrl eth orange on
			ledctrl eth white off
		fi
else if [ -z "$MSG3" ]			# These is for a specail case when IPv4 & IPv6 are PPPoE manual mode.
	then				# The wan & wan6 would be down, and the eth1 interface also disapear.
		ifconfig eth1 up
		ledctrl eth orange on
		ledctrl eth white off
	else
		ledctrl eth off
	fi
fi
}

wlan_led_handler()
{
	local ifUP;
	
	ifUP=$(ifconfig ra0 | grep UP | cut -d ' ' -f 11)
	
	[ -f /var/doing_wps ] && return

	if [ "$ifUP" == UP ]; then
		ledctrl wifi 2.4G on
	else
		ledctrl wifi 2.4G off
	fi
}

wlan5_led_handler()
{
	local ifUP;
	ifUP=$(ifconfig rax0 | grep UP | cut -d ' ' -f 11)
	
	[ -f /var/doing_wps ] && return
	
	if [ "$ifUP" == UP ]; then
		ledctrl wifi 5G on
	else
		ledctrl wifi 5G off
	fi
}

status_led_handler()
{
	if [ -f /var/ready ]; then 
		ledctrl power orange off
		ledctrl power white on
	else
		ledctrl power white off
		ledctrl power orange on	
	fi

}

while [ true ] ; do

	if [ -f /tmp/test_mode ]; then 
		sleep 2
	else
		eth_led_handler
		wlan_led_handler
		wlan5_led_handler
		status_led_handler
    sleep 2
	fi

done

