#!/bin/sh

# shellcheck disable=SC1090,SC3043,SC2039

# use the configure file at atmark-wwan-utils
CONFIG_FILE_CR_OLD="/etc/atmark/connection-recover/gsm-ttyMux0_connection-recover.conf"
CONFIG_FILE_CR_NEW="/etc/atmark/connection-recover.conf"

NAME=$(basename "$0")

PING_DEST_IP="8.8.8.8"

put_log () {
    echo "$NAME: $*"
    logger -t "$NAME" -- "$@"
}

is_wwan_connected () {
    for _ in $(seq 120)
    do
        local connection
        local modem_num
        if type mm-modem-num > /dev/null 2>&1; then
            modem_num=$(mm-modem-num) 2> /dev/null
        else
            modem_num=0
        fi
        connection=$(mmcli -m "$modem_num" -K 2>/dev/null | awk '$1 == "modem.generic.state" { print $3 }')
        case "$connection" in
        *connected*)
            return 0;;
        esac
        sleep 1
    done
    put_log "not wwan connected."
    return 1
}

is_ip_connected () {
    for _ in $(seq 3)
    do
        if ping -s 1 -c 5 -I ppp0 "$PING_DEST_IP" > /dev/null 2>&1; then
            return 0
        fi
        sleep 1
    done
    return 1
}

if [ -e "$CONFIG_FILE_CR_OLD" ]; then
    . "${CONFIG_FILE_CR_OLD}"
elif [ -e "$CONFIG_FILE_CR_NEW" ]; then
    . "${CONFIG_FILE_CR_NEW}"
fi

if [ -z "$PING_DEST_IP" ]; then
    put_log "warning: not configured PING_DEST_IP"
    exit 0
fi

if ! is_wwan_connected; then
    put_log "not connect wwan, do wan-force-restart"
    wwan-force-restart
    exit 0
fi

if ! is_ip_connected; then
    put_log "not connect wwan ip, do wan-force-restart"
    wwan-force-restart
fi
