#!/usr/bin/sh
set -u

STATE_DIR="/run/alteros-lte-l850-mm-config"
FATAL_STAMP="${STATE_DIR}/fatal.done"
RECOVERED_STAMP="/run/almi-lte-recover/recovered.done"
RUN_TIMEOUT_SEC=10

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_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
}

if [ -e "$FATAL_STAMP" ]; then
    log_msg "Fatal L850 marker exists; refusing to start ModemManager until successful almi-lte-recover or cold boot"
    exit 1
fi

if command -v journalctl >/dev/null 2>&1; then
    fatal_line="$(
        kernel_journal_after_recovery |
            grep -Ei 'iosm.*(A-CD_READY|CD_READY|msg timeout|PORT open refused|confused phase)|A-CD_READY|CD_READY' |
            tail -n 1
    )"
    if [ -n "$fatal_line" ]; then
        mark_fatal "Fatal iosm/XMM7360 marker before ModemManager start: $fatal_line"
        log_msg "Fatal iosm/XMM7360 marker exists; refusing to start ModemManager until successful almi-lte-recover or cold boot"
        exit 1
    fi
fi

exit 0
