#!/bin/sh /etc/rc.common
# Copyright (C) 2006 OpenWrt.org

START=95

#This function should be called
#-on boot
#-when wlan0 is disconnected
function logmsg() {
    MESSAGE=$1
    echo "$MESSAGE" > /dev/kmsg
    logger -t "done" "$MESSAGE"
}

function wan_wwan_ip_norelease() {
	uci set network.wan.norelease=1
	uci set network.wan6.norelease=1
	uci set network.wwan.norelease=1
	uci set network.wwan6.norelease=1
	uci commit
}
function restore_pending() {
    brightness=1
    LED=$1
    while [ 1 ]; do
        #echo $brightness > /sys/class/leds/$LED/brightness
        sleep 1
        if [[ "$brightness" == "1" ]]; then
            brightness=0
        else
            brightness=1
        fi
    done
}

function install_packages_after_sysupgrade() {
    MODEL=$1
    LED="G520-user1"
    case "$MODEL" in
        G5*)
            LED="G520-user1"
            ;;
        X3* | G4*)
            LED="X300-user1"
            ;;
        *)
            echo "unknown $MODEL series"
            ;;
    esac
    logmsg "OPKG: opkg update: MODEL:$MODEL, LED:$LED"
    restore_pending $LED &
    restorefn_pid=$!
    if [ -e /etc/backup/installed_packages.txt ]; then
        while [ 1 ]; do
            rc=`opkg update`
            logmsg "OPKG: opkg update: $rc"
            sleep 1
            rc=`opkg update 2>&1 1>/dev/null;echo $?`
            if [[ "$rc" == "0" ]]; then
                logmsg "OPKG: opkg updated"
                break
            fi
            logmsg "OPKG: waiting for opkg update!"
            sleep 120
        done
        installed=0
        failed=0
        for x in `cat /etc/backup/installed_packages.txt | awk '{if ($2=="overlay") print $1}'`;
        do
            is_installed=`opkg list-installed | grep "^$x "`
            logmsg "OPKG: checking package $x: $is_installed"
            if [[ "$is_installed" == "" ]]; then
                logmsg "OPKG: installing package $x"
                rc=`opkg install $x 2>&1 1>/dev/null;echo $?`
                if [[ "$rc" == "0" ]]; then
                    logmsg "OPKG: $x installed"
                    installed=$((installed+1))
                else
                    logmsg "OPKG: failed to install $x"
                    failed=$((failed+1))
                fi
            fi
            sleep 1
        done
        logmsg "OPKG: packages installed: $installed, failed: $failed"
        if [[ $failed -eq 0 ]]; then
            rm -f /etc/backup/installed_packages.txt
        fi
        if [[ $installed -gt 0 ]]; then
            #in case these packages were used in startup, lets reboot
            logmsg "OPKG: packages installed: $installed, reboot!"
            reboot
        fi
    fi
    logmsg "OPKG: packages installed: stop $restorefn_pid"
    kill $restorefn_pid
    wait $restorefn_pid 2>&1 1>/dev/null
    echo 0 > /sys/class/leds/$LED/brightness
    echo 0 > /sys/class/leds/$LED/brightness
}
function check_wifi() {
    sleep 120
    s=`ifstatus wwan | jq .errors[0].code`
    s6=`ifstatus wwan6 | jq .errors[0].code`
    if [[ "$s" != "null" ]] || [[ "$s6" != "null" ]]; then
        logmsg "check_wifi: $s, $s6"
        /etc/init.d/network reload
    fi
}
APP="firewallhandler"
lock_firewall() {
    while true; do
        if mkdir /var/lock/$APP; then
            logger -p "user.debug" "LTRX: init.d $APP$1 $$ : lock"
            break
        else
            logger -p "user.debug" "LTRX: init.d $APP$1 $$ : wait"
            usleep 500000
        fi
    done
}

unlock_firewall() {
    logger -p "user.debug" "LTRX: init.d $APP$1 $$ : unlock"
    rm -rf  /var/lock/$APP
}
boot() {
	mount_root done
	rm -f /sysupgrade.tgz && sync

	# process user commands
	[ -f /etc/rc.local ] && {
		sh /etc/rc.local
	}

	# set leds to normal state
	. /etc/diag.sh

	local model="$(cat /proc/device-tree/model)"
	case "$model" in
    *"Lantronix Mike Hawthorn"* | *"Lantronix Phil Hill"*)
        # sh /path/to/some/script.sh
        #increase the rpcd time
        timeout=`uci -q get rpcd.@rpcd[0].timeout || echo 60`
        if [[ $timeout -lt 300 ]]; then
            uci set rpcd.@rpcd[0].timeout='300'
            uci commit rpcd
            /etc/init.d/rpcd restart
        fi
        # enable SSH if upgrading from the 1.9 or before!
        needschange=`uci get dropbear.@dropbear_enable[0].enablessh 2>&1 | grep 'uci: Entry not found'`
        if [[ "$needschange" != "" ]]; then
            echo "ssh: $needschange" > /dev/kmsg
            uci add dropbear dropbear_enable
            uci set dropbear.@dropbear_enable[0].enablessh='1'
            uci commit dropbear
            /etc/init.d/dropbear reload
        fi
        #enable ssh if this is a T build
        if $(cat /etc/os-release | grep ^VERSION= | awk -F= '{print $2}' | grep -q T); then
            uci set dropbear.@dropbear_enable[0].enablessh='1'
            uci commit dropbear
            /etc/init.d/dropbear reload
        fi
        MODEL=`cat /proc/device-tree/lantronix/pid | awk '{print substr($0,0,4)}' | tr -d '\n'`
        [ "$MODEL" == "X30x" ] && {
            MODEL=`cat /proc/device-tree/lantronix/pid | awk '{print substr($0,6,4)}' | tr -d '\n'`
        }

        G526RP=`cat /proc/device-tree/lantronix/hwcfg 2>/dev/null | grep 'G526RP' | awk -F'sku=' '{print $2}' | awk -F',' '{print $1}' | awk '{print substr($0,0,6)}' | tr -d '\n'`
        if [[ "$G526RP" != "" ]]; then
            MODEL=$G526RP
        fi
        #SSH banner
        needschange=`cat /etc/banner | grep -eX300 -eG520 | wc -l`;
        logmsg "banner: $MODEL, update needed: $needschange"
        if [[ "$needschange" == "1" ]]; then
            case "$MODEL" in
            G5*)
                sed -i "s/G520/$MODEL/g" /etc/banner
            ;;
            X3* | G4*)
                sed -i "s/X300/$MODEL/g" /etc/banner
            ;;
            *)
                logmsg "banner: no change required for $MODEL"
            ;;
            esac
        fi
        lock_firewall
        DEVICE=`(ifstatus wwan6 || ifstatus wwan) | jq .device 2>/dev/null | tr -d "\"\n"`
        if [[ "$DEVICE" != "" ]]; then
            SSID=`wpa_cli -i"$DEVICE" status | grep ^ssid= | awk -F'ssid=' '{print $2}' | tr -d '\n'`
            logger -p "user.debug" "LTRX: init.d done->Connected to: $SSID"
            if [[ "x$SSID" != "xLantronix_Initial_Default_Infra" ]]; then
                    if [ -e /usr/sbin/firewall_update.sh ]; then
                        . /usr/sbin/firewall_update.sh
                        revert_firewall
                        logmsg "firewall: reverting rules!"
                    fi
            fi
        fi
        unlock_firewall
        #replace updates.d2sphere.com with update.lantronix.com
        sed -i "s/updates.d2sphere.com/update.lantronix.com/g"  /etc/opkg/distfeeds.conf
        #temporary workaround for opkg issues
        needschange=`cat /etc/opkg/distfeeds.conf | grep "update.lantronix.com" | grep -e"/X300/ipks/" -e"/G520/ipks/" -e"/G414/ipks/" | wc -l`;
        logmsg "distfeeds: $MODEL, update needed: $needschange"
        if [[ "$needschange" != "0" ]]; then
            case "$MODEL" in
            G5*)
                sed -i "/update.lantronix.com/ s/G520/$MODEL/g"  /etc/opkg/distfeeds.conf
            ;;
            X3* | G4*)
                sed -i "/update.lantronix.com/ s/X300/$MODEL/g" /etc/opkg/distfeeds.conf
            ;;
            *)
                logmsg "distfeeds1: no change required for $MODEL"
            ;;
            esac
            sed -i -re 's/^(option check_signature.*)/#\1/g' /etc/opkg.conf
        fi
        VERSION=`cat /etc/os-release  | grep VERSION= | awk -F'"' '{print $2}'`
        CURRENT_VERSION=`cat /etc/opkg/distfeeds.conf | grep "update.lantronix.com" | awk -F'ipks|main' '{print $2}' | tr -d '/'`
        has_correct_version=`cat /etc/opkg/distfeeds.conf | grep "update.lantronix.com" | grep "ipks/$VERSION/main" | wc -l`;
        if [[ "$has_correct_version" == "0" ]]; then
            if [[ "$CURRENT_VERSION" == "" ]]; then
                sed -i "/update.lantronix.com/ s/ipks\/main/ipks\/$VERSION\/main/g"  /etc/opkg/distfeeds.conf
            else
                sed -i "/update.lantronix.com/ s/ipks\/$CURRENT_VERSION\/main/ipks\/$VERSION\/main/g"  /etc/opkg/distfeeds.conf
            fi
        fi
        #switch back to unified firmware model
        needschange=`cat /etc/opkg/distfeeds.conf | grep "update.lantronix.com" | grep -e"/$MODEL/ipks/" | wc -l`;
        logmsg "distfeeds: $MODEL, update needed: $needschange"
        if [[ "$needschange" != "0" ]]; then
            case "$MODEL" in
            "G526" | "G527" | "G528")
                logmsg "integrated firmware ipks: MODEL:$MODEL"
                if [[ "$MODEL" != "G526RP" ]]; then
                    sed -i "/update.lantronix.com/ s/$MODEL/G520/g"  /etc/opkg/distfeeds.conf
                fi
            ;;
            X3*)
                sed -i "/update.lantronix.com/ s/$MODEL/X300/g" /etc/opkg/distfeeds.conf
            ;;
            *)
                logmsg "distfeeds2: no change required for $MODEL"
            ;;
            esac
            sed -i -re 's/^(option check_signature.*)/#\1/g' /etc/opkg.conf
        fi
        #SNMP OID
        oid=`uci -q get snmpd.@system[0].sysObjectID | tr -d '\n'`
        if [[ "$oid" == ".1.3.6.1.4.1.244.1.13" ]]; then
            id=`cat /proc/device-tree/lantronix/product_id | tr -d '\n'`
            if [ "$id" == "U1" ]; then
                uci set snmpd.@system[0].sysObjectID='.1.3.6.1.4.1.244.1.20'
            fi
            if [ "$id" == "U7" ]; then
                uci set snmpd.@system[0].sysObjectID='.1.3.6.1.4.1.244.1.21'
            fi
            uci commit snmpd
        fi
        #for X300: WiFi only
        if [[ "$MODEL" == "X300" ]]; then
            uci del network.cellular
            uci commit network.cellular
            uci del mwan3.cellular
            uci del mwan3.m5
            uci del_list mwan3.p1.use_member="m5"
            uci commit mwan3
            opkg remove luci-proto-3g
            opkg remove luci-proto-qmi
            rm -f /www/luci-static/resources/view/status/netinclude/20_cellular.js
            rm -f /etc/init.d/call_cellular
            rm -f /etc/init.d/call_cid_configuration
            rm -f /etc/init.d/cellular_monitor
            rm -f /etc/init.d/simtraydetection
            rm -f /etc/init.d/gps
        fi
        #install packages after sysupgrade, backgrounded
        #device will reboot if packages are installed.
        install_packages_after_sysupgrade $MODEL &
        #there is a case where WiFi is not initialzed
        #this is a temporary HACK!!!
        # check_wifi &
        
        #TODO! do we start console on lines here on boot?
        
		;;
	*"Lantronix SAM9X60 Production Loader")
		/usr/bin/ltrx_loader_cli &
		;;
	esac
	wan_wwan_ip_norelease &
	/etc/init.d/dnsmasq restart
	set_state done
}
