#!/usr/bin/sh
set -u

STATE_DIR="/run/alteros-lte-l850-mm-config"
STAMP="${STATE_DIR}/heal.done"
FATAL_STAMP="${STATE_DIR}/fatal.done"
RECOVERED_STAMP="/run/almi-lte-recover/recovered.done"
MAX_ATTEMPTS=2
MAX_RESTARTS=1
INITIAL_DELAY_SEC=25
RETRY_DELAY_SEC=30
RUN_TIMEOUT_SEC=10
RESTART_TIMEOUT_SEC=20

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

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

mark_done() {
    mkdir -p "$STATE_DIR"
    date -u '+%Y-%m-%dT%H:%M:%SZ' > "$STAMP"
}

mark_fatal() {
    reason="$1"
    mkdir -p "$STATE_DIR"
    {
        date -u '+%Y-%m-%dT%H:%M:%SZ'
        printf '%s\n' "$reason"
    } > "$FATAL_STAMP"
}

stamp_value() {
    key="$1"
    [ -s "$RECOVERED_STAMP" ] || return 1
    sed -n "s/^${key}=//p" "$RECOVERED_STAMP" | head -n 1
}

recovery_since_arg() {
    boot_id="$(stamp_value boot_id 2>/dev/null || true)"
    timestamp_epoch="$(stamp_value timestamp_epoch 2>/dev/null || true)"
    current_boot_id="$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || true)"

    case "$timestamp_epoch" in
        ''|*[!0-9]*)
            return 1
            ;;
    esac

    if [ -n "$boot_id" ] && [ -n "$current_boot_id" ] && [ "$boot_id" != "$current_boot_id" ]; then
        return 1
    fi

    printf '@%s\n' "$timestamp_epoch"
}

kernel_journal_after_recovery() {
    since_arg="$(recovery_since_arg 2>/dev/null || true)"
    if [ -n "$since_arg" ]; then
        run_limited "$RUN_TIMEOUT_SEC" journalctl -k -b --since "$since_arg" --no-pager -o cat 2>/dev/null
    else
        run_limited "$RUN_TIMEOUT_SEC" journalctl -k -b --no-pager -o cat 2>/dev/null
    fi
}

kernel_has_fatal_marker() {
    command -v journalctl >/dev/null 2>&1 || return 1
    kernel_journal_after_recovery |
        grep -Eiq 'iosm.*(A-CD_READY|CD_READY|msg timeout|PORT open refused|confused phase)|A-CD_READY|CD_READY'
}

stop_mm_after_fatal() {
    reason="$1"
    log_msg "$reason; stopping ModemManager; run almi-lte-recover or perform cold boot"
    mark_fatal "$reason"
    run_limited "$RESTART_TIMEOUT_SEC" systemctl stop ModemManager.service >/dev/null 2>&1 || :
    mark_done
    exit 0
}

first_modem_id() {
    run_limited "$RUN_TIMEOUT_SEC" mmcli -L 2>/dev/null | sed -n 's|.*Modem/\([0-9][0-9]*\).*|\1|p' | head -n 1
}

modem_value() {
    key="$1"
    printf '%s\n' "$2" | sed -n "s/^${key}[[:space:]]*[:=][[:space:]]*//p" | head -n 1
}

restart_mm() {
    log_msg "Restarting ModemManager after boot-time L850 SIM init problem"
    run_limited "$RESTART_TIMEOUT_SEC" systemctl restart ModemManager.service >/dev/null 2>&1 || :
}

if ! command -v mmcli >/dev/null 2>&1 || ! command -v systemctl >/dev/null 2>&1; then
    log_msg "mmcli or systemctl is not available; LTE boot heal skipped"
    exit 0
fi

sleep "$INITIAL_DELAY_SEC"

attempt=1
restart_count=0
while [ "$attempt" -le "$MAX_ATTEMPTS" ]; do
    if [ -e "$FATAL_STAMP" ] || kernel_has_fatal_marker; then
        stop_mm_after_fatal "Fatal iosm/XMM7360 marker detected before boot heal attempt ${attempt}"
    fi

    if ! run_limited "$RUN_TIMEOUT_SEC" systemctl -q is-active ModemManager.service; then
        log_msg "ModemManager is not active; LTE boot heal skipped"
        exit 0
    fi

    modem_id="$(first_modem_id)"
    if [ -z "$modem_id" ]; then
        log_msg "No ModemManager modem found on attempt ${attempt}/${MAX_ATTEMPTS}"
    else
        modem_info="$(run_limited "$RUN_TIMEOUT_SEC" mmcli -m "$modem_id" -K 2>/dev/null || true)"
        modem_state="$(modem_value modem.generic.state "$modem_info")"
        failed_reason="$(modem_value modem.generic.failed-reason "$modem_info")"

        case "$modem_state" in
            connected|registered|enabled|searching)
                log_msg "L850 modem state is ${modem_state}; boot heal is not needed"
                mark_done
                exit 0
                ;;
            failed)
                case "$failed_reason" in
                    sim-missing|SIM_MISSING|SimMissing)
                        log_msg "L850 modem is failed/sim-missing on attempt ${attempt}/${MAX_ATTEMPTS}"
                        if [ "$restart_count" -lt "$MAX_RESTARTS" ]; then
                            if kernel_has_fatal_marker; then
                                stop_mm_after_fatal "Fatal iosm/XMM7360 marker detected before ModemManager restart"
                            fi
                            restart_mm
                            restart_count=$((restart_count + 1))
                        else
                            log_msg "L850 sim-missing persisted after one safe restart; manual recovery or cold boot is required"
                            mark_done
                            exit 0
                        fi
                        ;;
                    *)
                        log_msg "L850 modem failed with reason '${failed_reason:-unknown}'; automatic reset is intentionally skipped"
                        mark_done
                        exit 0
                        ;;
                esac
                ;;
            *)
                log_msg "L850 modem state is '${modem_state:-unknown}'; waiting for NetworkManager"
                ;;
        esac
    fi

    if [ "$attempt" -lt "$MAX_ATTEMPTS" ]; then
        sleep "$RETRY_DELAY_SEC"
    fi
    attempt=$((attempt + 1))
done

log_msg "LTE boot heal reached ${MAX_ATTEMPTS} attempts and stopped; if LTE is still unavailable, run almi-lte-recover or perform cold boot"
mark_done
exit 0
