#!/bin/bash
# chlcd-board-support — i.MX8ULP 舊版 ODM 映像的系統層修補（CMA、WireGuard、開機程式＋dtb）。
#
#   chlcd-board-support state                         # 唯讀：硬體、映像、開機程式與每個修補的狀態（JSON）
#   chlcd-board-support apply [--tier-max N] [--plan] # 套用（冪等）。--plan 只列出還需要的修補、不動任何東西
#   chlcd-board-support undo <修補 id>                # 還原一個修補
#   chlcd-board-support flash-bootloader-keep-lights --i-have-uuu --expect-hostname <名稱> [--undo]   # 手動、tier 3
#
# 結束碼：0 沒有事要做／已完成；75 已套用、需要重開機；64 用法錯誤；其他（1）失敗。
# 判斷只看事實（dtb 內容、記憶體、md5），不看版本字串。完整說明：README.md、docs/spec/。

set -u

CBS_SELF="$(readlink -f "${BASH_SOURCE[0]}")"
CBS_ROOT="$(dirname "$CBS_SELF")/.."
if [ -z "${CBS_LIBDIR:-}" ]; then
    if [ -f "$CBS_ROOT/lib/chlcd-board-support/cma.sh" ]; then CBS_LIBDIR="$CBS_ROOT/lib/chlcd-board-support"; else CBS_LIBDIR="$CBS_ROOT/lib"; fi
fi
if [ -z "${CBS_CATALOG:-}" ]; then
    if [ -f "$CBS_LIBDIR/patches.conf" ]; then CBS_CATALOG="$CBS_LIBDIR/patches.conf"; else CBS_CATALOG="$CBS_ROOT/catalog/patches.conf"; fi
fi
if [ -z "${CBS_PAYLOAD:-}" ]; then
    if [ -d "$CBS_LIBDIR/payload" ]; then CBS_PAYLOAD="$CBS_LIBDIR/payload"; else CBS_PAYLOAD="$CBS_ROOT/payload"; fi
fi
if [ -z "${CBS_VERSION:-}" ]; then
    CBS_VERSION=$(cat "$CBS_LIBDIR/VERSION" "$CBS_ROOT/VERSION" 2>/dev/null | head -1)
    CBS_VERSION="${CBS_VERSION:-unknown}"
fi
export CBS_LIBDIR CBS_CATALOG CBS_PAYLOAD CBS_VERSION

# shellcheck source=/dev/null
. "$CBS_LIBDIR/cma.sh"
# shellcheck source=/dev/null
. "$CBS_LIBDIR/wireguard.sh"
# shellcheck source=/dev/null
. "$CBS_LIBDIR/lights.sh"

cbs_ids() { sed -n 's/^\[\(.*\)\]$/\1/p' "$CBS_CATALOG"; }

usage() {
    cat >&2 <<'USAGE'
用法：
  chlcd-board-support state
  chlcd-board-support apply [--tier-max N] [--plan]
  chlcd-board-support undo <修補 id>
  chlcd-board-support flash-bootloader-keep-lights --i-have-uuu --expect-hostname <主機名稱> [--undo]
結束碼：0 沒有事要做／已完成；75 已套用、需要重開機；64 用法錯誤；其他 失敗
USAGE
}

cmd_state() {
    local tsv id status detail
    tsv=$(mktemp) || return 1
    for id in $(cbs_ids); do
        IFS=$'\t' read -r status detail < <("$(cbs_cat "$id" condition)")
        printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$(cbs_cat "$id" layer)" "$(cbs_cat "$id" tier)" \
            "$(cbs_cat "$id" needs_reboot)" "$status" "$detail" "$(cbs_cat "$id" description)" "$(cbs_cat "$id" action)" >>"$tsv"
    done
    python3 -I "$CBS_LIBDIR/board-facts.py" state "$tsv"
    local rc=$?
    rm -f "$tsv"
    return $rc
}

cmd_apply() {
    local tier_max=1 plan=0 id tier status detail reboot=0 failed=0 rc act reb
    while [ $# -gt 0 ]; do
        case "$1" in
            --tier-max) tier_max="${2:-}"; shift ;;
            --plan) plan=1 ;;
            *) usage; return 64 ;;
        esac
        shift
    done
    case "$tier_max" in ''|*[!0-9]*) usage; return 64 ;; esac
    for id in $(cbs_ids); do
        tier=$(cbs_cat "$id" tier); act=$(cbs_cat "$id" action); reb=$(cbs_cat "$id" needs_reboot)
        if [ "$tier" -gt "$tier_max" ]; then
            op_log "$id：tier $tier 超過 --tier-max $tier_max，略過"
            continue
        fi
        case "$act" in manual:*) op_log "$id：只能手動（chlcd-board-support ${act#manual:}），略過"; continue ;; esac
        IFS=$'\t' read -r status detail < <("$(cbs_cat "$id" condition)")
        case "$status" in
            applied) op_log "$id：已套用（$detail）"; continue ;;
            not-applicable) op_log "$id：不適用（$detail）"; continue ;;
            needed) ;;
            *) op_err "$id：判斷不出狀態（$status）"; failed=1; continue ;;
        esac
        if [ "$plan" -eq 1 ]; then
            echo "PLAN $id tier=$tier reboot=$reb"
            continue
        fi
        op_log "$id：需要（$detail），套用中"
        rc=0
        "$act" || rc=$?
        if [ "$rc" -ne 0 ] && [ "$rc" -ne "$OP_REBOOT_EXIT" ]; then
            op_err "$id：套用失敗（結束碼 $rc）"
            "$(cbs_cat "$id" undo)" || true
            failed=1
            continue
        fi
        if ! "$(cbs_cat "$id" verify)"; then
            op_err "$id：套用後驗證不過，還原"
            "$(cbs_cat "$id" undo)" || true
            failed=1
            continue
        fi
        op_log "$id：已套用並驗證"
        [ "$rc" -eq "$OP_REBOOT_EXIT" ] && reboot=1
    done
    [ "$failed" -eq 0 ] || return 1
    [ "$reboot" -eq 0 ] || { op_log "需要重開機才會生效"; return "$OP_REBOOT_EXIT"; }
    return 0
}

cmd_undo() {
    local id="${1:-}"
    [ -n "$id" ] && cbs_ids | grep -qx "$id" || { op_err "不認得的修補：${id:-（沒給）}；有：$(cbs_ids | tr '\n' ' ')"; return 64; }
    "$(cbs_cat "$id" undo)"
}

case "${1:-}" in
    state) shift; cmd_state "$@" ;;
    apply) shift; cmd_apply "$@" ;;
    undo) shift; cmd_undo "$@" ;;
    flash-bootloader-keep-lights) shift; cbs_flash_keep "$@" ;;
    version|--version) echo "chlcd-board-support $CBS_VERSION" ;;
    *) usage; exit 64 ;;
esac
