#!/bin/sh

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

board_name=$(board_name)
modem=$(modem_name)

check_network() {
    miss_count="$(cat /tmp/miss_count 2>/dev/null)"
    [ -z "$miss_count" ] && miss_count=0
    mqtt_server=$(cat /app/config/mqtt_server.json | jsonfilter -e '@.host')
    ping -w3 -c 2 $mqtt_server >/dev/null 2>&1
    if [ "$?" != 0 ]; then
        rm -rf /tmp/net_ok
        miss_count=$(($miss_count + 1))
        echo "Network is abnormal, miss_count:$miss_count" | logger -t "supervisor_4g" -p 5
        if [ "${miss_count}" -gt "7" ]; then
            echo "4G card is reset, ${miss_count}" | logger -t "supervisor_4g" -p 5
            pcie_rst
            reset_modem
        fi
        if [ "${miss_count}" -gt "10" ]; 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
            sleep 10
            reboot -f
            miss_count=0
        fi
    else
        touch /tmp/net_ok
        miss_count=0
    fi
    echo "$miss_count" >/tmp/miss_count
}

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=0
while :; do
    sleep 2
    check_ports
    i=$((i + 1))
    if [ "$i" -gt 60 ]; then
        check_network &
        i=0
    fi
done
