#!/usr/bin/sh
set -u

PROFILE="/usr/lib/NetworkManager/system-connections/alteros-lte.nmconnection"
STATE_DIR="/run/alteros-lte-l850-mm-config"
FATAL_STAMP="${STATE_DIR}/fatal.done"
RUN_TIMEOUT_SEC=15

log_msg() {
    if command -v logger >/dev/null 2>&1; then
        logger -t alteros-lte-l850-mm-config -- "$*"
    fi
    echo "$*"
}

run_limited() {
    if command -v timeout >/dev/null 2>&1; then
        timeout "$RUN_TIMEOUT_SEC" "$@"
    else
        "$@"
    fi
}

loaded=0
wwan_enabled=0

if [ -e "$FATAL_STAMP" ]; then
    log_msg "Fatal L850 marker exists; WWAN setup skipped until successful almi-lte-recover or cold boot"
    exit 0
fi

if command -v nmcli >/dev/null 2>&1; then
    if run_limited nmcli connection reload >/dev/null 2>&1 || run_limited nmcli connection load "$PROFILE" >/dev/null 2>&1; then
        loaded=1
        log_msg "NetworkManager connection profile loaded"
    else
        log_msg "NetworkManager is not ready; setup skipped for this boot"
    fi

    if run_limited nmcli radio wwan on >/dev/null 2>&1; then
        wwan_enabled=1
        log_msg "WWAN radio enabled"
    else
        log_msg "WWAN radio was not enabled; setup skipped for this boot"
    fi
else
    log_msg "nmcli is not available; setup skipped for this boot"
fi

exit 0
