#!/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
}

line_is_fatal() {
    printf '%s\n' "$1" |
        grep -Eiq 'iosm.*(A-CD_READY|CD_READY|msg timeout|PORT open refused|confused phase)|A-CD_READY|CD_READY'
}

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
}

stop_mm() {
    reason="$1"
    log_msg "$reason; stopping ModemManager; run almi-lte-recover or perform cold boot"
    mark_fatal "$reason"
    if command -v systemctl >/dev/null 2>&1; then
        run_limited "$RUN_TIMEOUT_SEC" systemctl stop ModemManager.service >/dev/null 2>&1 || :
    fi
}

if [ -e "$FATAL_STAMP" ]; then
    stop_mm "Existing fatal L850 marker"
    exit 0
fi

if ! command -v journalctl >/dev/null 2>&1; then
    log_msg "journalctl is not available; L850 fatal guard skipped"
    exit 0
fi

existing_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 "$existing_line" ]; then
    stop_mm "Fatal iosm/XMM7360 marker already present: $existing_line"
    exit 0
fi

journalctl -k -f -n 0 -o cat 2>/dev/null | while IFS= read -r line; do
    if line_is_fatal "$line"; then
        stop_mm "Fatal iosm/XMM7360 marker detected: $line"
        exit 0
    fi
done

exit 0
