#!/bin/sh

. /lib/functions.sh
. /lib/dyiot/bin/get_hardware

board_name=$(board_name)
modem=$(modem_name)
mqtt_server=$(/app/lnxall_decrypto_read /app/config/mqtt_server.json | jsonfilter -e '@.host')
mqtt_port=$(/app/lnxall_decrypto_read /app/config/mqtt_server.json | jsonfilter -e '@.port')
miss_count=0
dont_reboot="/app/config/dont_check_network"

write_reboot_log() {
	if [ -e "$1" ] ; then
		local logs="`ls -l $1 | awk '{print $5}'`"
		if [ -z "${logs}" ] ; then
			rm -rf "$1"
		elif [ ${logs} -gt 131072 ] ; then
			rm -rf "$1"
		fi
	fi
	echo "$2" >> "$1"
}

check_network() {
    [ -z "$miss_count" ] && miss_count=0
    nc -zv $mqtt_server $mqtt_port >/dev/null 2>&1
    if [ "$?" != 0 ]; then
        rm -rf /tmp/net_ok
        miss_count=$(($miss_count + 1))
        if [ ! -f "$dont_reboot" ]; then
            echo "Network is abnormal, miss_count:$miss_count" | logger -t "supervisor_4g" -p 5
            local remainder=$(($miss_count % 70))
            if [ "${remainder}" = "0" ]; then
                echo "4G card is reset, ${miss_count}" | logger -t "supervisor_4g" -p 5
                pcie_rst
                reset_modem
            fi
            if [ "${miss_count}" -gt "500" ]; then
                echo "reboot as network cannot recover,${miss_count}" | logger -t "supervisor_4g" -p 3
                echo "reboot as network cannot recover,${miss_count}" >/dev/console
                /etc/init.d/cloud_mqtt stop
                killall cloud_mqtt
                sleep 5
                cd /tmp
                tar -czvf /app/REPORT_DB.tar.gz *_REPORT_*.db*
                write_reboot_log "/app/network_failure_reboot.log" "check_network reboot: `date`, `uptime`"
                sync
                sleep 10
                reboot -f
                miss_count=0
            fi
        fi
    else
        touch /tmp/net_ok
        miss_count=0
    fi
}

check_ports() {
    if [ "$board_name" == "WOOLINK-MT7621-512M-256M" ]; then
        cur_status="$(swconfig dev switch0 port 4 get link | awk -F'[ :]' '{print $4}')"
        if test -n "$old_status" && [ "x$cur_status" != "x$old_status" ]; then
            echo "WAN port link status changed $old_status->$cur_status" | logger -t "supervisor_4g" -p 3
            ifconfig eth0.4094 down
            ifconfig eth0.4094 up
        fi
        old_status=$cur_status
    elif [ "$board_name" == "WOOLINK-MT7628-128M-32M" ]; then
        cur_status="$(swconfig dev switch0 port 0 get link | awk -F'[ :]' '{print $4}')"
        if test -n "$old_status" && [ "x$cur_status" != "x$old_status" ]; then
            echo "WAN port link status changed $old_status->$cur_status" | logger -t "supervisor_4g" -p 3
            ifconfig eth0.4090 down
            ifconfig eth0.4090 up
        fi
        old_status=$cur_status
    fi
}

i=3
while :; do
    sleep 2
    check_ports
    i=$((i + 1))
    if [ "$i" -gt 5 ]; then
        check_network
        i=0
    fi
done
