#!/bin/sh

source /etc/utils/shell-utils.sh
LOG_FILE=/var/logs/infomir-init.log
DEBUG=1

percent2value() {
    if [ "$1" -le "10" ]; then
        tmp=$(($1*5/10))
    elif [ "$1" -ge "100" ]; then
        tmp=255
    else
        tmp=$(($1-10))
        tmp=$(($tmp*250/90))
        tmp=$(($tmp+5))
    fi
    echo $tmp
}

get_led_type() {
    num="506"
    echo $num > /sys/class/gpio/export
    echo "in" > /sys/class/gpio/gpio$num/direction
    tmp=`cat /sys/class/gpio/gpio$num/value`
    echo $num > /sys/class/gpio/unexport
    export $1=$tmp
}

defaultLedLevel=`fw_printenv defaultLedLevel 2>/dev/null`
defaultLedLevel=${defaultLedLevel#defaultLedLevel=}
if [ "$defaultLedLevel" = "" ]; then
    get_model_ext model
    if [ "$model" == "MAG524" ] || [ "$model" == "MAG544" ]; then
        defaultLedLevel="10"
    else
        defaultLedLevel="30"
    fi
    fw_setenv defaultLedLevel $defaultLedLevel 2>/dev/null 1>/dev/null
fi

standbyLedLevel=`fw_printenv standbyLedLevel 2>/dev/null`
standbyLedLevel=${standbyLedLevel#standbyLedLevel=}
if [ "$standbyLedLevel" = "" ]; then
    get_model_ext model
    if [ "$model" == "MAG524" ] || [ "$model" == "MAG544" ]; then
        standbyLedLevel="20"
    else
        standbyLedLevel="100"
    fi
    fw_setenv standbyLedLevel $standbyLedLevel 2>/dev/null 1>/dev/null
fi

redLedLevel=`fw_printenv redLedLevel 2>/dev/null`
redLedLevel=${redLedLevel#redLedLevel=}
if [ "$redLedLevel" = "" ]; then
    get_model_ext model
    if [ "$model" == "MAG524" ] || [ "$model" == "MAG544" ]; then
        redLedLevel="10"
    else
        redLedLevel="45"
    fi
    fw_setenv redLedLevel $redLedLevel 2>/dev/null 1>/dev/null
fi

${SPLASH} prg 20
${SPLASH} clear_log
${SPLASH} log "Init LEDs..."

# Setup LEDs
if [ "$#" == "0" ]; then
    get_led_type led_type
    if [ "$led_type" == "0" ]; then
        insmod /lib/modules/4.9.113/kernel/drivers/amlogic/led/led.ko legacy_board=1
    else
        insmod /lib/modules/4.9.113/kernel/drivers/amlogic/led/led.ko
    fi
else
    echo 1 > /sys/class/leds/mag-front-led/brightness
    echo blinker > /sys/class/leds/mag-front-led/trigger
fi

echo 50 > /sys/class/leds/mag-front-led/delay_on
echo 50 > /sys/class/leds/mag-front-led/delay_off
echo $(percent2value $standbyLedLevel) > /sys/class/leds/mag-front-led/level
echo $(percent2value $defaultLedLevel) > /sys/class/leds/mag-front-led/level_off
echo 3 > /sys/class/leds/mag-front-led/cnt
echo $redLedLevel > /sys/class/leds/red/level

log "LED subsystem init DONE."