#!/usr/bin/bash
set -u

DEV="${ALMI_LTE_DEV:-0000:57:00.0}"
ROOT_PORT="${ALMI_LTE_ROOT_PORT:-0000:00:1c.0}"
PXSX="${ALMI_LTE_ACPI_PATH:-\\_SB.PC00.RP08.PXSX}"
GOOD_VDID="${ALMI_LTE_GOOD_VDID:-0x73608086}"
MAX_ATTEMPTS="${MAX_ATTEMPTS:-2}"
STATE_DIR="/run/almi-lte-recover"
LOCK_FILE="${STATE_DIR}/recover.lock"
RECOVERED_STAMP="${STATE_DIR}/recovered.done"
CONFIG_STATE_DIR="/run/alteros-lte-l850-mm-config"
CONFIG_FATAL_STAMP="${CONFIG_STATE_DIR}/fatal.done"
RUN_TIMEOUT_SEC="${RUN_TIMEOUT_SEC:-20}"
PROBE_WAIT_SEC="${PROBE_WAIT_SEC:-25}"
ROOT_PC_PATH=""
ROOT_PC_PREV=""
ROOT_PC_HELD=0

AUTO=0
FORCE=0
DRY_RUN=0

usage() {
    cat <<'EOF'
Usage: almi-lte-recover [--auto] [--force] [--dry-run]

Recover Fibocom L850-GL / Intel XMM7360 on HP EliteBook 840 G10 from
off-bus or A-CD_READY state using the validated ACPI sequence:
remove -> PXSX.SHRF -> PXSX._RST -> root-port rescan.

Exit codes:
  0 healthy/no-op or recovered
  1 recovery attempted but failed
  2 acpi_call or prerequisite is unavailable
  3 unsupported platform/path in manual mode
  4 another recovery is already running
  5 ModemManager could not be stopped safely
EOF
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        --auto) AUTO=1 ;;
        --force|--allow-unsupported) FORCE=1 ;;
        --dry-run) DRY_RUN=1 ;;
        -h|--help) usage; exit 0 ;;
        *)
            echo "Unknown argument: $1" >&2
            usage >&2
            exit 3
            ;;
    esac
    shift
done

log_msg() {
    echo "[almi-lte-recover] $*"
    if command -v logger >/dev/null 2>&1; then
        logger -t almi-lte-recover -- "$*"
    fi
}

restore_root_port_power_control() {
    [ "$ROOT_PC_HELD" -eq 1 ] || return 0

    if [ -n "$ROOT_PC_PATH" ] && [ -w "$ROOT_PC_PATH" ]; then
        if echo "$ROOT_PC_PREV" > "$ROOT_PC_PATH" 2>/dev/null; then
            log_msg "restored root port ${ROOT_PORT} runtime PM power/control=${ROOT_PC_PREV}"
        else
            log_msg "warning: failed to restore ${ROOT_PC_PATH}=${ROOT_PC_PREV}"
        fi
    fi

    ROOT_PC_HELD=0
    ROOT_PC_PATH=""
    ROOT_PC_PREV=""
}

cleanup_and_exit() {
    code="$1"
    restore_root_port_power_control
    exit "$code"
}

hold_root_port_awake() {
    root_path="$1"
    root_pc="${root_path}/power/control"

    ROOT_PC_HELD=0
    ROOT_PC_PATH=""
    ROOT_PC_PREV=""

    [ -e "$root_pc" ] || return 0

    if [ ! -w "$root_pc" ]; then
        log_msg "warning: ${root_pc} is not writable; continuing without runtime PM hold"
        return 0
    fi

    ROOT_PC_PREV="$(cat "$root_pc" 2>/dev/null || true)"
    [ -n "$ROOT_PC_PREV" ] || ROOT_PC_PREV="auto"

    if echo on > "$root_pc" 2>/dev/null; then
        ROOT_PC_PATH="$root_pc"
        ROOT_PC_HELD=1
        log_msg "holding root port ${ROOT_PORT} runtime PM active: power/control=on (was ${ROOT_PC_PREV})"
    else
        log_msg "warning: failed to set ${root_pc}=on; continuing without runtime PM hold"
        ROOT_PC_PREV=""
    fi
}

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

auto_noop_or_exit() {
    code="$1"
    shift
    log_msg "$*"
    if [ "$AUTO" -eq 1 ]; then
        exit 0
    fi
    exit "$code"
}

require_root() {
    if [ "$(id -u)" -ne 0 ]; then
        log_msg "must be run as root"
        exit 2
    fi
}

prepare_state() {
    mkdir -p "$STATE_DIR" "$CONFIG_STATE_DIR"
}

take_lock() {
    exec 9>"$LOCK_FILE"
    if ! flock -n 9; then
        auto_noop_or_exit 4 "another recovery instance is already running"
    fi
}

product_name() {
    cat /sys/class/dmi/id/product_name 2>/dev/null || true
}

sys_vendor() {
    cat /sys/class/dmi/id/sys_vendor 2>/dev/null || true
}

platform_supported_by_dmi() {
    [ "$FORCE" -eq 1 ] && return 0
    [ "${ALMI_LTE_ALLOW_UNSUPPORTED:-0}" = "1" ] && return 0

    vendor="$(sys_vendor)"
    product="$(product_name)"

    case "$vendor:$product" in
        *HP*:*EliteBook*840*G10*|*Hewlett-Packard*:*EliteBook*840*G10*)
            return 0
            ;;
    esac
    return 1
}

ensure_supported_platform() {
    if ! platform_supported_by_dmi; then
        auto_noop_or_exit 3 "unsupported platform: vendor='$(sys_vendor)' product='$(product_name)'"
    fi
}

ensure_acpi_call() {
    if [ -e /proc/acpi/call ]; then
        return 0
    fi

    if command -v modprobe >/dev/null 2>&1 && modprobe acpi_call 2>/dev/null; then
        [ -e /proc/acpi/call ] && return 0
    fi

    log_msg "acpi_call is unavailable; install/build acpi_call-dkms for kernel $(uname -r)"
    exit 2
}

acpi_call() {
    method="$1"
    printf '%s\n' "$method" > /proc/acpi/call 2>/dev/null || return 1
    tr -d '\0' < /proc/acpi/call 2>/dev/null || true
}

vdid() {
    acpi_call "${PXSX}.VDID"
}

ensure_acpi_path() {
    value="$(vdid)"
    case "$value" in
        0x73608086|0xffffffff|0xFFFFFFFF)
            return 0
            ;;
        Error*|"")
            auto_noop_or_exit 3 "unsupported ACPI path ${PXSX}: VDID='${value}'"
            ;;
    esac
}

kernel_lines_since() {
    since_epoch="$1"
    if ! command -v journalctl >/dev/null 2>&1; then
        return 1
    fi

    if [ "$since_epoch" -gt 0 ]; then
        run_limited journalctl -k -b --since "@${since_epoch}" --no-pager -o cat 2>/dev/null
    else
        run_limited journalctl -k -b --no-pager -o cat 2>/dev/null
    fi
}

kernel_has_attach_since() {
    since_epoch="$1"
    kernel_lines_since "$since_epoch" | grep -Eiq 'iosm.*(port|wwan).*attached|wwan.*attached'
}

kernel_has_fail_since() {
    since_epoch="$1"
    kernel_lines_since "$since_epoch" | grep -Eiq 'iosm.*(probe failed|BAR .*not claimed|can.t enable device|A-CD_READY|CD_READY|msg timeout|PORT open refused|confused phase)|probe failed|BAR .*not claimed'
}

rpc_state() {
    [ -e /dev/wwan0xmmrpc0 ] || { echo NOPORT; return; }
    python3 - <<'PY'
import os
try:
    fd = os.open('/dev/wwan0xmmrpc0', os.O_RDWR | os.O_SYNC | os.O_NONBLOCK)
except OSError as exc:
    print("EIO" if exc.errno == 5 else "ERR")
else:
    os.close(fd)
    print("OK")
PY
}

is_healthy() {
    since_epoch="${1:-0}"
    [ "$(vdid)" = "$GOOD_VDID" ] || return 1
    [ "$(rpc_state)" = "OK" ] || return 1
    if [ "$since_epoch" -gt 0 ]; then
        kernel_has_attach_since "$since_epoch" || return 1
        ! kernel_has_fail_since "$since_epoch" || return 1
    fi
    return 0
}

vdid_is_good() {
    [ "$1" = "$GOOD_VDID" ]
}

vdid_is_offbus() {
    case "$1" in
        0xffffffff|0xFFFFFFFF)
            return 0
            ;;
    esac
    return 1
}

wait_for_rpc_state() {
    seconds="${1:-$PROBE_WAIT_SEC}"
    elapsed=0

    while [ "$elapsed" -lt "$seconds" ]; do
        state="$(rpc_state)"
        case "$state" in
            OK|EIO|ERR)
                printf '%s\n' "$state"
                return 0
                ;;
        esac
        sleep 1
        elapsed=$((elapsed + 1))
    done

    rpc_state
}

soft_blocked() {
    [ "$(vdid)" = "$GOOD_VDID" ] || return 1
    command -v rfkill >/dev/null 2>&1 || return 1
    rfkill list 2>/dev/null |
        awk 'BEGIN{IGNORECASE=1} /wwan|wan|modem/{w=1} w && /Soft blocked: yes/{print "yes"; exit}' |
        grep -q yes
}

unblock_wwan_if_needed() {
    if soft_blocked; then
        log_msg "rfkill soft-block detected with live VDID; unblocking WWAN without ACPI power-cycle"
        [ "$DRY_RUN" -eq 1 ] && return 0
        rfkill unblock wwan 2>/dev/null || rfkill unblock all 2>/dev/null || true
        sleep 2
    fi
}

legacy_rpc_service_active() {
    command -v systemctl >/dev/null 2>&1 || return 1
    systemctl is-active --quiet alteros-lte-l850.service 2>/dev/null
}

stop_modemmanager() {
    command -v systemctl >/dev/null 2>&1 || return 0

    if legacy_rpc_service_active; then
        auto_noop_or_exit 5 "alteros-lte-l850.service is active; refusing to recover while another RPC owner may hold the port"
    fi

    if systemctl list-unit-files ModemManager.service >/dev/null 2>&1; then
        log_msg "stopping ModemManager before ACPI recovery"
        [ "$DRY_RUN" -eq 1 ] && return 0
        if ! run_limited systemctl stop ModemManager.service >/dev/null 2>&1; then
            log_msg "failed to stop ModemManager safely; recovery not started"
            exit 5
        fi
    fi
}

power_cycle_once() {
    log_msg "ACPI recovery: remove -> ${PXSX}.SHRF -> ${PXSX}._RST -> rescan"

    if [ "$DRY_RUN" -eq 1 ]; then
        return 0
    fi

    dev_path="/sys/bus/pci/devices/${DEV}"
    root_path="/sys/bus/pci/devices/${ROOT_PORT}"
    result=1

    hold_root_port_awake "$root_path"

    while :; do
        if [ -e "${dev_path}/remove" ]; then
            if ! echo 1 > "${dev_path}/remove"; then
                log_msg "failed to remove PCI device ${DEV}"
                break
            fi
            sleep 1
        fi

        if ! acpi_call "${PXSX}.SHRF" >/dev/null; then
            log_msg "ACPI ${PXSX}.SHRF failed"
            break
        fi
        sleep 2

        if ! acpi_call "${PXSX}._RST" >/dev/null; then
            log_msg "ACPI ${PXSX}._RST failed"
            break
        fi
        sleep 3

        if [ ! -e "${root_path}/rescan" ]; then
            log_msg "root port ${ROOT_PORT} rescan path is missing"
            break
        fi

        # 1.0-4: базу журнала для oracle берём НЕПОСРЕДСТВЕННО перед rescan, чтобы
        # fail-окно не захватывало предсмертные 'msg timeout' старого iosm-инстанса
        # (до remove) и не браковало успешную attempt 1 ложно (README §37).
        start_epoch="$(date +%s)"
        if ! echo 1 > "${root_path}/rescan"; then
            log_msg "failed to rescan root port ${ROOT_PORT}"
            break
        fi

        for _ in $(seq 1 20); do
            [ -e "/sys/bus/pci/devices/${DEV}" ] && break
            sleep 1
        done

        for _ in $(seq 1 20); do
            [ -e /dev/wwan0xmmrpc0 ] && break
            sleep 1
        done

        sleep 2
        if is_healthy "$start_epoch"; then
            result=0
        fi
        break
    done

    restore_root_port_power_control
    return "$result"
}

write_recovered_stamp() {
    {
        echo "boot_id=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || true)"
        echo "timestamp_epoch=$(date +%s)"
        echo "timestamp_iso=$(date -Is)"
        echo "dev=${DEV}"
        echo "root_port=${ROOT_PORT}"
        echo "acpi_path=${PXSX}"
        echo "vdid=$(vdid)"
        echo "rpc=$(rpc_state)"
    } > "$RECOVERED_STAMP"
}

mark_failure() {
    {
        echo "timestamp_epoch=$(date +%s)"
        echo "timestamp_iso=$(date -Is)"
        echo "reason=almi-lte-recover failed"
        echo "vdid=$(vdid)"
        echo "rpc=$(rpc_state)"
    } > "$CONFIG_FATAL_STAMP"
}

finish_success() {
    if [ "$DRY_RUN" -eq 1 ]; then
        log_msg "dry-run: recovery path reached; state files were not changed"
        exit 0
    fi

    write_recovered_stamp
    rm -f "$CONFIG_FATAL_STAMP"
    if command -v systemctl >/dev/null 2>&1; then
        systemctl reset-failed ModemManager.service >/dev/null 2>&1 || true
        systemctl reset-failed alteros-lte-l850-mm-config-guard.service >/dev/null 2>&1 || true
        systemctl start alteros-lte-l850-mm-config-guard.service >/dev/null 2>&1 || true
    fi
    log_msg "recovery success: VDID=$(vdid), RPC=$(rpc_state)"
    exit 0
}

main() {
    require_root
    prepare_state
    take_lock
    ensure_supported_platform
    ensure_acpi_call
    ensure_acpi_path

    current_vdid="$(vdid)"
    current_rpc="$(rpc_state)"

    if vdid_is_good "$current_vdid"; then
        unblock_wwan_if_needed
        current_rpc="$(rpc_state)"

        case "$current_rpc" in
            OK)
                log_msg "modem is healthy; no recovery needed"
                exit 0
                ;;
            NOPORT)
                log_msg "VDID is live but RPC port is missing; waiting up to ${PROBE_WAIT_SEC}s for iosm probe"
                current_rpc="$(wait_for_rpc_state "$PROBE_WAIT_SEC")"
                case "$current_rpc" in
                    OK)
                        log_msg "RPC port appeared after iosm probe; no recovery needed"
                        exit 0
                        ;;
                    EIO)
                        log_msg "RPC returned EIO after probe wait; treating as recoverable A-CD_READY"
                        ;;
                    *)
                        log_msg "VDID is live but RPC=${current_rpc}; assuming iosm is still probing or driver is not ready, not ACPI power-cycling"
                        exit 0
                        ;;
                esac
                ;;
            EIO)
                log_msg "VDID is live but RPC returned EIO; treating as recoverable A-CD_READY"
                ;;
            *)
                log_msg "VDID is live but RPC=${current_rpc}; not ACPI power-cycling"
                exit 0
                ;;
        esac
    elif vdid_is_offbus "$current_vdid"; then
        log_msg "VDID=${current_vdid}; treating as recoverable off-bus state"
    else
        log_msg "unsupported modem state: VDID=${current_vdid}, RPC=${current_rpc}; not ACPI power-cycling"
        exit 1
    fi

    if vdid_is_good "$current_vdid" && [ "$current_rpc" != "EIO" ]; then
        if is_healthy 0; then
            log_msg "modem became healthy; no recovery needed"
            exit 0
        fi
    fi

    log_msg "modem is recoverable-dead: VDID=$(vdid), RPC=$(rpc_state); starting bounded recovery"
    stop_modemmanager

    attempt=1
    while [ "$attempt" -le "$MAX_ATTEMPTS" ]; do
        log_msg "recovery attempt ${attempt}/${MAX_ATTEMPTS}"
        if power_cycle_once; then
            finish_success
        fi
        log_msg "attempt ${attempt} failed: VDID=$(vdid), RPC=$(rpc_state)"
        attempt=$((attempt + 1))
    done

    mark_failure
    log_msg "recovery failed after ${MAX_ATTEMPTS} attempts; manual analysis or cold boot is required"
    exit 1
}

trap 'restore_root_port_power_control' EXIT
trap 'cleanup_and_exit 130' INT
trap 'cleanup_and_exit 143' TERM

main "$@"
