#!/bin/sh /etc/rc.common
# (C) 2008 openwrt.org

START=60

load_led() {
	local name
	local sysfs
	local trigger
	local dev
	local mode
	local default
	local delayon
	local delayoff

	config_get name $1 name
	config_get sysfs $1 sysfs
	config_get trigger $1 trigger
	config_get dev $1 dev
	config_get mode $1 mode
	config_get default $1 default
	config_get delayon $1 delayon
	config_get delayoff $1 delayoff

	[ -e /sys/class/leds/${sysfs}/brightness ] && {
		logger "setting up led : ${name:-$sysfs}"
		[ -n "$default" ] && { 
			[ $default -eq 1 ] && 
				echo 1 >/sys/class/leds/${sysfs}/brightness 
			[ $default -eq 1 ] ||
				echo 0 >/sys/class/leds/${sysfs}/brightness
		}
		[ -z "$trigger" ] && trigger=none
		echo $trigger > /sys/class/leds/${sysfs}/trigger
		[ "$trigger" == "netdev" -a -n "$dev" ] && {
			[ -z "$mode" ] && mode=link
			echo $dev > /sys/class/leds/${sysfs}/device_name
			echo $mode > /sys/class/leds/${sysfs}/mode
		} 
		[ "$trigger" == "timer" ] && {
			[ -n "$delayon" ] && echo $delayon > /sys/class/leds/${sysfs}/delay_on
			[ -n "$delayoff" ] && echo $delayoff > /sys/class/leds/${sysfs}/delay_off
		}
	}
}

start() {
	[ -e /sys/class/leds/ ] && {
		config_load system
		config_foreach load_led led
	}
	# flash ACT LED for vigor
	/etc/led-control.sh act &

	# control HNAT LED
	hnat=$(uci get router.shnat.enable)
    if [ $hnat -eq "1" ]; then
        echo on > /proc/gpio/LED6
    else
        echo off > /proc/gpio/LED6
    fi
	
	# control QoS LED
    head -1 /etc/config/switch/ratelimit | grep ".*/.*/.*/1/.*/.*"
	# WAN shaper on
    if [ "$?" -eq "0" ]; then	
        echo on > /proc/gpio/LED5
    else
        echo off > /proc/gpio/LED5
    fi

	# control DoS LED
	wifi=$(uci -P /var/state get network.lan.wifi_device 2>/dev/null || echo 0)
	if [ $wifi -ne "1" ]; then
		cat /etc/config/switch/stormconfig | grep -q "1/.*/.*" && echo on > /proc/gpio/LED1 || echo off > /proc/gpio/LED1
	fi
	
	# for USB p1 p2 LED
        dev_num=$(grep -c Lev=02.*Port=01 /proc/bus/usb/devices)
        if [ $dev_num = "1" ]; then
                # USB1 on
                echo on > /proc/gpio/LED2
        else
                echo off > /proc/gpio/LED2
        fi

        dev_num=$(grep -c Lev=02.*Port=02 /proc/bus/usb/devices)
        if [ $dev_num = "1" ]; then
                # USB2 on
                echo on > /proc/gpio/LED3
        else
                echo off > /proc/gpio/LED3
        fi
	
	# for WPS LED
	wps=$(uci get wireless.@wifi-iface[0].encryption 2>/dev/null)
	wifi=$(uci get wireless.ra0.radio 2>/dev/null)
	if [ $wps = "wps" -a $wifi = "1" ]; then
		echo on > /proc/gpio/LED7
	else
		echo off > /proc/gpio/LED7
	fi
}
