#!/bin/bash
# amos — package manager and dependency resolver for AM·OS


# Global flags are accepted in any position:
#   amos --dry-run install vim    and    amos install --dry-run vim
# both work.

set -euo pipefail
export LC_ALL=C

MIRRORS_FILE="${MIRRORS_FILE:-/etc/amos/mirrors}"
CACHE_DIR="${CACHE_DIR:-/var/cache/amos}"
TMP_ROOT="${TMP_ROOT:-$CACHE_DIR/downloads}"
DEPS_NAME="amos64/deps.conf"       # relative to the mirror root
CHECKSUMS_NAME="CHECKSUMS.md5"     # relative to the mirror root
GPG_KEY_NAME="AMOS-GPG-KEY"       # relative to the mirror root
SERIES_ROOT="amos64"               # prefix of package entries inside CHECKSUMS.md5
INSTALLED_DIR="/var/log/packages"
PIN_FILE="${PIN_FILE:-/etc/amos/key.fingerprint}"
FORCE_KEY_ROTATE=0
NETMODE_TIMER="${NETMODE_TIMER:-7200}"
BLACKLIST_FILE="${BLACKLIST_FILE:-/etc/amos/blacklist}"
declare -a BLACKLIST=()
FORCE_BLACKLIST=0
CHECK_IMPACT=0
HARD_CLEAN=0
SUPPRESS_NETMODE_STRICT=0
AMOS_NETMODE="${AMOS_NETMODE:-open}"
USER="radanne"
PASSWORD="uhADWeT7wL7zmh99G4SQPQfDAxQEYhzX8PAvepyUFxmvY1kTa"

declare -A SERIES_PRIO=(
    [a]=10 [ap]=20 [d]=30 [k]=40 [l]=50 [n]=60
    [tcl]=70 [x]=80 [xap]=90 [xfce]=100 [y]=110 [z]=200
)
declare -A PKG_PRIO_OVERRIDE=()
# Packages that install/upgrade skip when they appear as transitive deps.
# Only 'amos full-upgrade' (or naming them explicitly on the command line)
# upgrades them. glibc and gcc are the toolchain: a mid-transaction upgrade
# to either can break running binaries or compiled objects.
declare -a ESSENTIAL_PKGS=(
    glibc
    aaa_glibc-solibs
    gcc
    gcc-g++
)

# Packages whose upgrades should precede everything else in full-upgrade.
# These are the tools upgradepkg itself uses to unpack and install. If a
# future release changes their CLI in a way that matters, this ordering
# prevents a half-installed system.
declare -a BOOTSTRAP_PKGS=(
    xz
    zstd
    bzip2
    gzip
    tar
    coreutils
    bash
    pkgtools
)

is_essential() {
    local p="$1" e
    for e in "${ESSENTIAL_PKGS[@]}"; do
        [ "$e" = "$p" ] && return 0
    done
    return 1
}

DRY_RUN=0
REINSTALL=0
NO_AUTO_UPDATE=0
FETCH_ERROR=""
# Review scope for .new config files after a transaction:
#   scoped  (install, upgrade)  - only packages in this transaction
#   all     (upgrade-all, full-upgrade) - every .new file under the /etc sun
POST_INSTALL_REVIEW="scoped"

trap 'netmode strict; exit 130' INT
trap 'netmode strict; exit 143' TERM

# Colors
C_RESET=$'\e[0m'
C_GREEN=$'\e[32m'
C_RED=$'\e[31m'
C_YELLOW=$'\e[33m'
C_CYAN=$'\e[36m'
C_BOLD=$'\e[1m'
C_DIM=$'\e[2m'

log()     { printf '%s\n' "$*" >&2; }
info()    { printf "${C_CYAN}[INFO]${C_RESET} %s\n" "$*" >&2; }
warn()    { printf "${C_YELLOW}[WARN]${C_RESET} %s\n" "$*" >&2; }
error()   { printf "${C_RED}[ERROR]${C_RESET} %s\n" "$*" >&2; }
success() { printf "${C_GREEN}[OK]${C_RESET} %s\n" "$*" >&2; }
header()  { printf "\n${C_BOLD}${C_CYAN}=== %s ===${C_RESET}\n" "$*" >&2; }

die() { 
    error "$*"
    netmode strict
    exit 1; 
}
debug() { [ -n "${AMOS_DEBUG:-}" ] || return 0; printf "${C_DIM}[DEBUG] %s${C_RESET}\n" "$*" >&2; }
have()  { command -v "$1" >/dev/null 2>&1; }

# Format a 40/64-char fingerprint as "ABCD 1234 ..." for readability.
fmt_fp() {
    printf '%s\n' "$1" | sed 's/\(....\)/\1 /g; s/ $//'
}

# Extract the first fingerprint from a key file WITHOUT importing it.
gpg_key_fingerprint() {
    local keyfile="$1"
    gpg --show-keys --with-colons "$keyfile" 2>/dev/null \
        | awk -F: '/^fpr:/ {print $10; exit}'
}

check_key_pin() {
    local keyfile="$1"
    local mode="${2:-allow-create}"
    local fp pinned

    [ -s "$keyfile" ] || { warn "no key file at $keyfile to pin"; return 0; }

    fp=$(gpg_key_fingerprint "$keyfile")
    if [ -z "$fp" ]; then
        error "could not compute fingerprint for $keyfile"
        error "the fetched key may be malformed; refusing to proceed"
        return 1
    fi

    if [ ! -s "$PIN_FILE" ]; then
        if [ "$mode" = "require-pin" ]; then
            error "no key pin at $PIN_FILE"
            error "run 'amos update' first to establish trust"
            return 1
        fi
        mkdir -p "$(dirname "$PIN_FILE")"
        printf '%s\n' "$fp" > "$PIN_FILE"
        chmod 644 "$PIN_FILE"
        header "GPG KEY PINNED (first-time trust)"
        log "  fingerprint: $(fmt_fp "$fp")"
        log "  saved to:    $PIN_FILE"
        log ""
        warn "VERIFY THIS OUT-OF-BAND against the AM·OS key fingerprint"
        log "published in the release announcement / website. If it"
        log "does not match, stop and investigate immediately."
        return 0
    fi

    pinned=$(cat "$PIN_FILE")
    if [ "$fp" = "$pinned" ]; then
        debug "key pin OK: $(fmt_fp "$fp")"
        return 0
    fi

    if [ "$FORCE_KEY_ROTATE" -eq 1 ]; then
        warn "GPG key fingerprint changed"
        log "  pinned:  $(fmt_fp "$pinned")"
        log "  fetched: $(fmt_fp "$fp")"
        warn "accepting rotation due to --force-key-rotate"

        if gpg --list-keys --with-colons "$pinned" >/dev/null 2>&1; then
            warn "the OLD key is still in the keyring; remove it manually"
            log "         if you want strict single-key trust: gpg --delete-keys $pinned"
        else
            debug "pinned fingerprint $pinned is not in the keyring; nothing to remove"
        fi

        printf '%s\n' "$fp" > "$PIN_FILE"
        return 0
    fi

    error "GPG key fingerprint mismatch — refusing to proceed"
    log "  pinned:  $(fmt_fp "$pinned")  ($PIN_FILE)"
    log "  fetched: $(fmt_fp "$fp")"
    log ""
    log "  If the AM·OS maintainer rotated the key AND you have verified"
    log "  the new fingerprint through a trusted channel, re-run with:"
    log "    amos update --force-key-rotate"
    return 1
}

for t in awk sort installpkg upgradepkg gpg md5sum; do
    have "$t" || die "required tool not found: $t"
done

mkdir -p "$CACHE_DIR" "$TMP_ROOT"

# ---------------------------------------------------------------------------
# Help
# ---------------------------------------------------------------------------

cmd_help() {
    local fp_line pin_line
    if [ -s "${PIN_FILE:-/etc/amos/key.fingerprint}" ]; then
        fp_line=$(fmt_fp "$(cat "${PIN_FILE:-/etc/amos/key.fingerprint}")")
        pin_line="${PIN_FILE:-/etc/amos/key.fingerprint}"
    else
        fp_line="(not yet pinned — run 'amos update' to fetch and pin the key)"
        pin_line="/etc/amos/key.fingerprint (not yet created)"
    fi

    cat <<EOF
amos — package manager and dependency resolver for AM·OS

Usage:
  amos update                    Refresh deps.conf, CHECKSUMS.md5, GPG key, and packages.idx
  amos install [opts] PKG...     Install PKGs and their dependencies
  amos upgrade [opts] PKG...     Upgrade PKGs and everything that depends on them
  amos upgrade-all [opts]        Upgrade every package with a newer version in the repo
  amos full-upgrade [opts]       Upgrade everything including essential packages
                                 (glibc, gcc) with priority ordering
  amos deps PKG                  Show forward dependencies (what PKG needs)
  amos rdeps PKG                 Show reverse dependencies (what needs PKG)
  amos list [PATTERN]            List packages in the repo index (optionally filtered)
  amos blacklist                 List entries in /etc/amos/blacklist
  amos configs                   Review leftover .new config files under the /etc sun
  amos check                     Sanity-check the repo metadata
  amos clean [--dry-run] [--hard] Remove cached packages not referenced by the current 
                                 index. Use --hard to wipe the entire cache.
  amos help                      Show this help

Options (accepted anywhere on the command line):
  --dry-run             Resolve, sort, and print the plan; do not fetch or install
  --reinstall           Act even if the package is already at the repo version
  --check-impact        Before installing/upgrading, run 'whoneeds' and 'needswhat' 
                        to show forward and reverse dependencies for each target
  --force               Ignore /etc/amos/blacklist for this invocation. Affects
                        only the blacklist; GPG, IMA, key pin, and toolchain
                        checks still apply.
  --netmode MODE        Network mode for this invocation: 'open' (default,
                        through Tor) or 'clearnet' (direct). Strict is
                        refused because it would block all downloads.
  --force-key-rotate    Accept a new GPG key fingerprint; use ONLY after
                        verifying the new fingerprint out-of-band
  -h, --help            Show this help

Environment:
  MIRRORS_FILE     default /etc/amos/mirrors
  CACHE_DIR        default /var/cache/amos
  TMP_ROOT         default \$CACHE_DIR/downloads
  PIN_FILE         default /etc/amos/key.fingerprint
  BLACKLIST_FILE   default /etc/amos/blacklist
  AMOS_DEBUG=1     Enable debug logging (GET URLs, wget exit codes, stderr)
  NETMODE_TIMER    default 3600; per-package network-open seconds
  AMOS_NETMODE     default open; 'clearnet' bypasses Tor (IPv6 / Tor-blocked)

Network access:
  update, install, upgrade, upgrade-all, and full-upgrade switch the
  system from "netmode strict" to "netmode open" (through Tor) for
  the duration of network activity, then back to strict on completion.

  Set AMOS_NETMODE=clearnet or pass --netmode clearnet to fetch over
  the direct internet instead. Needed when Tor is blocked by the
  network, when the system Tor daemon is unhealthy, or on IPv6-only
  hosts (open mode does not redirect IPv6; see Section 5.3 of the
  manual). Clearnet mode exposes fetch traffic to the ISP and to the
  mirror operator. The system still reverts to strict on completion.

  The timer is re-armed per package during multi-package downloads,
  so no single fetch is cut off. If the script crashes mid-download,
  the timer auto-reverts to strict on its own. Install and index-build
  phases always run with network already strict.

Essential packages:
  glibc, aaa_glibc-solibs, gcc, and gcc-g++ are treated as essential.
  'install', 'upgrade', and 'upgrade-all' will not touch them as
  transitive dependencies; only 'full-upgrade' or an explicit name
  on the command line will upgrade them. This keeps mid-transaction
  toolchain upgrades out of routine package operations.

Blacklist:
  \$BLACKLIST_FILE lists packages that should never be installed or
  upgraded. One package name or shell glob per line; '#' starts a
  comment.

  - 'upgrade-all' and 'full-upgrade' silently skip blacklisted packages.
  - 'install X' and 'upgrade X' die if X is blacklisted unless --force
    is given. A blacklisted transitive dependency in 'install' also dies,
    because a partial install would produce a broken binary.
  - 'full-upgrade' refuses to run if an essential package is both
    blacklisted and stale, because full-upgrade is the command that
    upgrades the toolchain.
  - 'update', 'check', 'clean', 'list', and 'blacklist' are not affected.

GPG key pin:
  fingerprint: $fp_line
  pinned at:   $pin_line
  This is the ONLY key amos will trust for package and index signatures.
  If it does not match the AM·OS key fingerprint published out-of-band,
  stop and investigate before running any install/upgrade command.

Config file merges (.new files):
  On install/upgrade, amos prompts for .new files belonging to the
  packages in the current transaction. A .new file you skipped earlier
  is offered again the next time its package is involved in a
  transaction, so a skipped merge is deferred, not dismissed.

  upgrade-all and full-upgrade prompt for every .new file under /etc,
  unconditionally. 'amos configs' does the same on demand, without
  requiring an install or upgrade first.

  Actions: keep old (discard .new), replace (back up current to .bak,
  install .new), diff, skip (defer), and batch variants applied to all
  remaining files. /etc/passwd, /etc/shadow, /etc/group, and their
  backups are never auto-overwritten; they are always flagged for
  manual merge.


Examples:
  AMOS_DEBUG=1 amos update
  amos install --dry-run vim
  amos upgrade --reinstall glibc
  amos list '^x'
  amos blacklist
  amos clean --dry-run
amos install --check-impact vim
  amos deps sqlite
  amos rdeps libpng
EOF
}

# ---------------------------------------------------------------------------
# Mirrors
# ---------------------------------------------------------------------------

load_mirrors() {
    [ -f "$MIRRORS_FILE" ] || die "mirrors file not found: $MIRRORS_FILE"
    mapfile -t MIRRORS < <(grep -vE '^[[:space:]]*(#|$)' "$MIRRORS_FILE" | sed 's/[[:space:]]*$//')
    [ ${#MIRRORS[@]} -gt 0 ] || die "no mirrors defined in $MIRRORS_FILE"
}


FETCH_MAX_ATTEMPTS="${FETCH_MAX_ATTEMPTS:-30}"

fetch_file() {
    local remote="$1" dest="$2" url attempt full rc errf stderr_msg code
    local ua="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"
    local last_size cur_size wait_s

    mkdir -p "$(dirname "$dest")"
    errf="$(mktemp)"
    FETCH_ERROR=""
    FETCH_URL=""
    FETCH_RC=""
    FETCH_HTTP=""

    [ ${#MIRRORS[@]} -gt 0 ] || die "no mirrors loaded (load_mirrors was not called)"

    for url in "${MIRRORS[@]}"; do
        url="${url%/}"
        last_size=-1
        for attempt in $(seq 1 "$FETCH_MAX_ATTEMPTS"); do
            full="$url/$remote"
            debug "GET $full"
            debug "  -> $dest (attempt $attempt/$FETCH_MAX_ATTEMPTS)"

            rc=0
            stderr_msg=""
            code=""

            if [ -t 2 ]; then
                local cols name name_short bar_width initial_size start_time elapsed
                local this_bytes speed_bps speed_str pct filled empty bar spaces
                local eta_str remaining cur_size last_size wget_log wget_pid
                local total_size=0 pct_known

                cols=$(tput cols </dev/tty 2>/dev/null || echo 80)
                [ -n "$cols" ] && [ "$cols" -ge 40 ] 2>/dev/null || cols=80

                name=$(basename "$dest")
                if [ ${#name} -gt 20 ]; then
                    name_short="${name:0:17}..."
                else
                    name_short="$name"
                fi

                bar_width=$(( cols - 60 ))
                [ "$bar_width" -lt 10 ] && bar_width=10

                initial_size=$(stat -c %s "$dest" 2>/dev/null || echo 0)
                start_time=$(date +%s)
                wget_log=$(mktemp)

                rc=0
                # Using -q to completely silence wget, preventing terminal garbage
                wget --user="${USER:-}" --password="${PASSWORD:-}" \
                    --user-agent="$ua" \
                    --tries=1 --continue \
                    --connect-timeout=20 --read-timeout=60 \
                    -q -S -O "$dest" "$full" 2>"$wget_log" &
                wget_pid=$!

                last_size=-1
                while kill -0 "$wget_pid" 2>/dev/null; do
                    sleep 0.2

                    if [ "$total_size" -eq 0 ] && [ -s "$wget_log" ]; then
                        total_size=$(grep -i 'Content-Length:' "$wget_log" 2>/dev/null \
                                    | tail -1 | awk '{print $2}' | tr -d '\r')
                        [ -n "$total_size" ] && [ "$total_size" -gt 0 ] 2>/dev/null || total_size=0
                    fi

                    cur_size=$(stat -c %s "$dest" 2>/dev/null || echo 0)
                    [ "$cur_size" = "$last_size" ] && continue
                    last_size=$cur_size

                    elapsed=$(( $(date +%s) - start_time ))
                    [ "$elapsed" -lt 1 ] && elapsed=1
                    this_bytes=$(( cur_size - initial_size ))
                    [ "$this_bytes" -lt 0 ] && this_bytes=0
                    speed_bps=$(( this_bytes / elapsed ))

                    if [ "$speed_bps" -ge 1048576 ]; then
                        speed_str=$(awk -v s="$speed_bps" 'BEGIN{printf "%.1fMB/s", s/1048576}')
                    elif [ "$speed_bps" -ge 1024 ]; then
                        speed_str="$((speed_bps / 1024))KB/s"
                    else
                        speed_str="${speed_bps}B/s"
                    fi

                    if [ "$total_size" -gt 0 ]; then
                        pct=$(( cur_size * 100 / total_size ))
                        [ "$pct" -gt 100 ] && pct=100
                        filled=$(( pct * bar_width / 100 ))
                        empty=$(( bar_width - filled ))
                        bar=$(printf '%*s' "$filled" "" | tr ' ' '=')
                        spaces=$(printf '%*s' "$empty" "")

                        if [ "$speed_bps" -gt 0 ] && [ "$total_size" -gt "$cur_size" ]; then
                            remaining=$(( (total_size - cur_size) / speed_bps ))
                            if   [ "$remaining" -ge 3600 ]; then eta_str="$((remaining/3600))h$((remaining%3600/60))m"
                            elif [ "$remaining" -ge 60   ]; then eta_str="$((remaining/60))m$((remaining%60))s"
                            else                                 eta_str="${remaining}s"
                            fi
                        else
                            eta_str="--"
                        fi

                        # \033[K at the end clears any trailing characters
                        printf $'\r\e[K%s[%d/%d]%s %-20s %3d%%[%s%s] %10s %8s\033[K' \
                            "$C_CYAN" "$attempt" "$FETCH_MAX_ATTEMPTS" "$C_RESET" \
                            "$name_short" "$pct" "$bar" "$spaces" "$speed_str" "$eta_str" >&2
                    else
                        local cur_human
                        cur_human=$(numfmt --to=iec "$cur_size" 2>/dev/null || echo "${cur_size}B")
                        printf $'\r\e[K%s[%d/%d]%s %-20s %10s %10s\033[K' \
                            "$C_CYAN" "$attempt" "$FETCH_MAX_ATTEMPTS" "$C_RESET" \
                            "$name_short" "$cur_human" "$speed_str" >&2
                    fi
                done

                wait "$wget_pid" || rc=$?
                printf $'\r\e[K' >&2

                [ -s "$wget_log" ] && stderr_msg=$(tr '\n' ' ' <"$wget_log" | sed 's/  */ /g; s/^ //; s/ $//')
                code=$(grep -oE 'HTTP/[0-9.]+ [0-9]{3}' "$wget_log" 2>/dev/null | tail -1 | awk '{print $2}')
                rm -f "$wget_log"
            else
                wget --user="${USER:-}" --password="${PASSWORD:-}" \
                    --user-agent="$ua" \
                    --tries=1 --waitretry=0 --continue \
                    --connect-timeout=20 --read-timeout=60 \
                    --server-response --no-verbose \
                    -O "$dest" "$full" 2>"$errf" || rc=$?
                [ -s "$errf" ] && stderr_msg=$(tr '\n' ' ' <"$errf" | sed 's/  */ /g; s/^ //; s/ $//')
                code=$(grep -oE 'HTTP/[0-9.]+ [0-9]{3}' "$errf" 2>/dev/null \
                        | tail -1 | awk '{print $2}')
            fi

            if [ "$rc" -eq 0 ]; then
                debug "OK $full (attempt $attempt)"
                rm -f "$errf"
                return 0
            fi

            FETCH_URL="$full"
            FETCH_RC="$rc"
            FETCH_HTTP="$code"
            FETCH_ERROR="last attempt $attempt/$FETCH_MAX_ATTEMPTS: $full"
            [ -n "$code" ] && FETCH_ERROR="$FETCH_ERROR (http $code)"
            [ -n "$stderr_msg" ] && FETCH_ERROR="$FETCH_ERROR: $stderr_msg"

            debug "wget exit=$rc http=${code:-?} url=$full"

            if [ "$rc" -eq 3 ]; then
                error "write failed for $dest (wget exit 3); aborting"
                rm -f "$errf"
                return 1
            fi
            if [ "$rc" -eq 6 ] || [ "$code" = "401" ] || [ "$code" = "403" ]; then
                warn "http ${code:-auth} for $full; trying next mirror"
                break
            fi
            if [ "$rc" -eq 5 ]; then
                warn "SSL verification failed for $full; trying next mirror"
                break
            fi
            if [ "$code" = "404" ]; then
                warn "http 404 for $full; trying next mirror"
                break
            fi

            cur_size=$(stat -c %s "$dest" 2>/dev/null || echo 0)
            if [ "$last_size" -ge 0 ] && [ "$cur_size" -gt "$last_size" ]; then
                if [ -t 2 ]; then
                    printf $'\r\e[K%s[%d/%d]%s %-20s retry (progress: %s bytes)\033[K' \
                        "$C_YELLOW" "$attempt" "$FETCH_MAX_ATTEMPTS" "$C_RESET" "$name_short" "$cur_size" >&2
                else
                    warn "retry $attempt/$FETCH_MAX_ATTEMPTS for $remote (progress: $cur_size bytes, wget rc=$rc)"
                fi
                last_size=$cur_size
                continue
            fi
            last_size=$cur_size

            wait_s=0
            if [ -t 2 ]; then
                printf $'\r\e[K%s[%d/%d]%s %-20s waiting %ds (rc=%d)\033[K' \
                    "$C_YELLOW" "$attempt" "$FETCH_MAX_ATTEMPTS" "$C_RESET" "$name_short" "$wait_s" "$rc" >&2
            else
                warn "retry $attempt/$FETCH_MAX_ATTEMPTS for $remote (no progress at $cur_size bytes, wget rc=$rc, sleeping ${wait_s}s)"
            fi
            sleep "$wait_s"

        done
    done
    rm -f "$errf"
    return 1
}

# ---------------------------------------------------------------------------
# Index from CHECKSUMS.md5
# ---------------------------------------------------------------------------

build_index() {
    local cs="$CACHE_DIR/$CHECKSUMS_NAME"
    local idx="$CACHE_DIR/packages.idx"
    [ -s "$cs" ] || die "CHECKSUMS.md5 missing; run 'amos update'"

    : > "$idx"
    awk -v sroot="$SERIES_ROOT" '
        /^[0-9a-f]{32}[[:space:]]+\./ {
            md5 = $1
            path = $2
            sub(/^\.\//, "", path)
            if (path ~ /\.(txz|tgz)$/) {
                n = split(path, parts, "/")
                if (n >= 3 && parts[1] == sroot) {
                    series = parts[2]
                    file   = parts[n]
                    fullid = file
                    sub(/\.(txz|tgz)$/, "", fullid)
                    name = fullid
                    sub(/-[0-9].*$/, "", name)
                    printf "%s|%s|%s|%s|%s\n", name, fullid, series, path, md5
                }
            }
        }
    ' "$cs" | sort -t'|' -k1,1 > "$idx"

    [ -s "$idx" ] || die "no packages found in CHECKSUMS.md5"
    success "Indexed $(wc -l < "$idx") packages"
}


# ---------------------------------------------------------------------------
# Blacklist
# ---------------------------------------------------------------------------

load_blacklist() {
    BLACKLIST=()
    [ -f "$BLACKLIST_FILE" ] || return 0
    local line
    while IFS= read -r line || [ -n "$line" ]; do
        line="${line%%#*}"
        line="${line#"${line%%[![:space:]]*}"}"
        line="${line%"${line##*[![:space:]]}"}"
        [ -z "$line" ] && continue
        BLACKLIST+=("$line")
    done < "$BLACKLIST_FILE"
    [ ${#BLACKLIST[@]} -gt 0 ] && \
        debug "blacklist: ${#BLACKLIST[@]} pattern(s) from $BLACKLIST_FILE"
    return 0
}

is_blacklisted() {
    local pkg="$1" pat
    [ ${#BLACKLIST[@]} -eq 0 ] && return 1
    for pat in "${BLACKLIST[@]}"; do
        # shellcheck disable=SC2254
        case "$pkg" in
            $pat) return 0 ;;
        esac
    done
    return 1
}

maybe_note_ignored_edges() {
    local list="$1"; shift
    [ "$IGNORED_EDGE_COUNT" -eq 0 ] && return 0
    local p
    for p in "$@"; do
        case " $list " in
            *" $p "*)
                warn "edge: $IGNORED_EDGE_COUNT dependency edge(s) suppressed for this transaction (see /etc/amos/edge-ignore-deps.conf)"
                return 0
                ;;
        esac
    done
}

load_deps() {
    local depsfile="$CACHE_DIR/$DEPS_NAME"
    [ -s "$depsfile" ] || die "deps.conf missing; run 'amos update'"
    declare -gA PKG_DEPS=()
    declare -gA REVERSE=()

    local -A ignore_edge=()
    local -A used_edge=()
    declare -g IGNORED_EDGE_COUNT=0
    declare -g IGNORED_EDGE_SRCS=""
    declare -g IGNORED_EDGE_DSTS=""
    local is_edge=0
    local ignore_file=/etc/amos/edge-ignore-deps.conf
    local raw pkg dep d line rest filtered

    if [ -f /etc/amos/edition ] && grep -q "edge" /etc/amos/edition; then
        is_edge=1
        if [ -f "$ignore_file" ]; then
            while IFS= read -r raw || [ -n "$raw" ]; do
                raw="${raw%%#*}"
                raw="${raw#"${raw%%[![:space:]]*}"}"
                raw="${raw%"${raw##*[![:space:]]}"}"
                [ -z "$raw" ] && continue
                [[ "$raw" == *:* ]] || continue
                pkg="${raw%%:*}"
                dep="${raw#*:}"
                pkg="${pkg%"${pkg##*[![:space:]]}"}"
                dep="${dep#"${dep%%[![:space:]]*}"}"
                # shellcheck disable=SC2086
                for d in $dep; do
                    ignore_edge["$pkg $d"]=1
                done
            done < "$ignore_file"
        else
            warn "edge edition but $ignore_file missing; dependency graph NOT filtered"
        fi
    fi

    while IFS= read -r line; do
        [[ "$line" =~ ^[[:space:]]*# ]] && continue
        [[ -z "${line// /}" ]] && continue
        read -r pkg rest <<< "$line"
        filtered=""
        # shellcheck disable=SC2086
        for d in $rest; do
            if [ "$is_edge" -eq 1 ] && [ -n "${ignore_edge["$pkg $d"]:-}" ]; then
                debug "edge: dropping dependency $pkg -> $d"
                IGNORED_EDGE_COUNT=$((IGNORED_EDGE_COUNT + 1))
                IGNORED_EDGE_SRCS+=" $pkg"
                IGNORED_EDGE_DSTS+=" $d"
                used_edge["$pkg $d"]=1
                continue
            fi
            filtered+=" $d"
        done
        filtered="${filtered# }"
        PKG_DEPS[$pkg]="$filtered"
        # shellcheck disable=SC2086
        for d in $filtered; do
            REVERSE[$d]+=" $pkg"
        done
    done < "$depsfile"

    if [ ${#ignore_edge[@]} -gt 0 ]; then
        local key
        for key in "${!ignore_edge[@]}"; do
            [ -n "${used_edge["$key"]:-}" ] || \
                warn "$ignore_file entry '$key' has no matching edge in deps.conf"
        done
    fi
}

# ---------------------------------------------------------------------------
# Installed state
# ---------------------------------------------------------------------------

installed_fullid() {
    local pkg="$1" f base
    for f in "$INSTALLED_DIR/${pkg}-"*; do
        [ -e "$f" ] || continue
        base=$(basename "$f")
        case "$base" in
            "${pkg}-"[0-9]*) printf '%s\n' "$base"; return 0 ;;
        esac
    done
    return 0
}

needs_update() {
    local pkg="$1" mirror_fullid="$2" inst
    inst=$(installed_fullid "$pkg")
    [ "$inst" != "$mirror_fullid" ]
}

series_of() {
    awk -F'|' -v p="$1" '$1==p {print $3; exit}' "$CACHE_DIR/packages.idx"
}

fullid_of() {
    awk -F'|' -v p="$1" '$1==p {print $2; exit}' "$CACHE_DIR/packages.idx"
}

relpath_of() {
    awk -F'|' -v p="$1" '$1==p {print $4; exit}' "$CACHE_DIR/packages.idx"
}

md5_of() {
    awk -F'|' -v p="$1" '$1==p {print $5; exit}' "$CACHE_DIR/packages.idx"
}

resolve_pkg_name() {
    local p="$1"
    awk -F'|' -v p="$p" '
        $1==p {print $1; exit}
        $2==p {print $1; exit}
    ' "$CACHE_DIR/packages.idx"
}

# ---------------------------------------------------------------------------
# Closures
# ---------------------------------------------------------------------------

direct_closure() {
    local -A seen=()
    local queue=("$@") p
    while [ ${#queue[@]} -gt 0 ]; do
        p="${queue[0]}"
        queue=("${queue[@]:1}")
        [ -n "${seen[$p]:-}" ] && continue
        seen[$p]=1
        printf '%s\n' "$p"
        for d in ${PKG_DEPS[$p]:-}; do
            queue+=("$d")
        done
    done
}

reverse_closure() {
    local -A seen=()
    local queue=("$@") p
    while [ ${#queue[@]} -gt 0 ]; do
        p="${queue[0]}"
        queue=("${queue[@]:1}")
        [ -n "${seen[$p]:-}" ] && continue
        seen[$p]=1
        printf '%s\n' "$p"
        for r in ${REVERSE[$p]:-}; do
            queue+=("$r")
        done
    done
}

# ---------------------------------------------------------------------------
# Kahn topological sort
# ---------------------------------------------------------------------------

topo_sort() {
    local -a pkgs=("$@")
    local -A indeg=() adj=() series_cache=() processed=()
    local p d s q prio

    for p in "${pkgs[@]}"; do
        indeg[$p]=0
        series_cache[$p]=$(series_of "$p")
    done

    for p in "${pkgs[@]}"; do
        for d in ${PKG_DEPS[$p]:-}; do
            if [ -n "${indeg[$d]:-}" ]; then
                adj[$d]+=" $p"
                indeg[$p]=$((indeg[$p] + 1))
            fi
        done
    done

    local -a result=()
    local remaining=${#pkgs[@]}
    local best best_prio best_name

    while [ "$remaining" -gt 0 ]; do
        best=""
        best_prio=999999
        best_name=""
        for q in "${pkgs[@]}"; do
            [ -n "${processed[$q]:-}" ] && continue
            [ "${indeg[$q]}" -eq 0 ] || continue
            s="${series_cache[$q]}"
            if [ -n "${PKG_PRIO_OVERRIDE[$q]:-}" ]; then
                prio="${PKG_PRIO_OVERRIDE[$q]}"
            else
                prio="${SERIES_PRIO[$s]:-999}"
            fi
            if [ -z "$best" ] || [ "$prio" -lt "$best_prio" ] || \
               { [ "$prio" -eq "$best_prio" ] && [[ "$q" < "$best_name" ]]; }; then
                best="$q"
                best_prio="$prio"
                best_name="$q"
            fi
        done

        if [ -z "$best" ]; then
            debug "dependency cycle detected; falling back to series order for remaining"
            if [ ${#result[@]} -gt 0 ]; then
                printf '%s\n' "${result[@]}"
            fi
            for q in "${pkgs[@]}"; do
                [ -n "${processed[$q]:-}" ] && continue
                printf '%s %s\n' "${SERIES_PRIO[${series_cache[$q]}]:-999}" "$q"
            done | sort -k1,1n -k2 | awk '{print $2}'
            return
        fi

        result+=("$best")
        processed[$best]=1
        remaining=$((remaining - 1))
        for d in ${adj[$best]:-}; do
            indeg[$d]=$((indeg[$d] - 1))
        done
    done

    printf '%s\n' "${result[@]}"
}

# ---------------------------------------------------------------------------
# Plan printer
# ---------------------------------------------------------------------------

print_plan() {
    local verb="$1" scope_label="$2" n_scope="$3" n_skip="$4"
    shift 4
    local -a ordered=("$@")
    local i=0 p s fid

    header "${verb^} Plan (${scope_label}=${n_scope}, to ${verb}=${#ordered[@]}, up to date=${n_skip})"
    if [ ${#ordered[@]} -gt 0 ]; then
        for p in "${ordered[@]}"; do
            i=$((i+1))
            s=$(series_of "$p")
            fid=$(fullid_of "$p")
            printf '  %2d. %s%-6s%s %s\n' "$i" "$C_DIM" "$s" "$C_RESET" "$fid" >&2
        done
    fi
}

# ---------------------------------------------------------------------------
# Download + verify + install
# ---------------------------------------------------------------------------

verify_md5() {
    local file="$1" expected="$2" got
    got=$(md5sum "$file" | awk '{print $1}')
    [ "$got" = "$expected" ]
}

verify_gpg() {
    local file="$1" asc="$2"
    gpg --verify "$asc" "$file" >/dev/null 2>&1
}

purge_stale_cache() {
    local pkg="$1" keep_dest="$2" keep_asc="$3"
    local f
    local -a stale=()

    while IFS= read -r -d '' f; do
        [ "$f" = "$keep_dest" ] && continue
        [ "$f" = "$keep_asc"  ] && continue
        stale+=("$f")
    done < <(find "$TMP_ROOT" -type f \
                \( -name "${pkg}-[0-9]*.txz" \
                -o -name "${pkg}-[0-9]*.txz.asc" \
                -o -name "${pkg}-[0-9]*.tgz" \
                -o -name "${pkg}-[0-9]*.tgz.asc" \) \
                -print0 2>/dev/null)

    if [ ${#stale[@]} -gt 0 ]; then
        for f in "${stale[@]}"; do
            debug "purge stale cache: $(basename "$f")"
            rm -f "$f"
        done
    fi
}

review_new_configs() {
    local scope_all=0
    local -a pkgs=()
    while [ $# -gt 0 ]; do
        case "$1" in
            --all) scope_all=1; shift ;;
            --)    shift; while [ $# -gt 0 ]; do pkgs+=("$1"); shift; done ;;
            *)     pkgs+=("$1"); shift ;;
        esac
    done
    if [ "$scope_all" -eq 0 ] && [ ${#pkgs[@]} -eq 0 ]; then
        scope_all=1
    fi

    declare -A FULLID_OF_PATH=()
    local p fid logfile rel
    if [ "$scope_all" -eq 1 ]; then
        for logfile in "$INSTALLED_DIR"/*; do
            [ -e "$logfile" ] || continue
            fid=$(basename "$logfile")
            while IFS= read -r rel || [ -n "$rel" ]; do
                rel="${rel%$'\r'}"
                rel="${rel#./}"
                rel="${rel#/}"
                rel="${rel%/}"
                case "$rel" in
                    etc/*) FULLID_OF_PATH["/$rel"]="$fid" ;;
                esac
            done < "$logfile"
        done
    else
        for p in "${pkgs[@]}"; do
            fid=$(installed_fullid "$p")
            [ -n "$fid" ] || continue
            logfile="$INSTALLED_DIR/$fid"
            [ -f "$logfile" ] || continue
            while IFS= read -r rel || [ -n "$rel" ]; do
                rel="${rel%$'\r'}"
                rel="${rel#./}"
                rel="${rel#/}"
                rel="${rel%/}"
                case "$rel" in
                    etc/*) FULLID_OF_PATH["/$rel"]="$fid" ;;
                esac
            done < "$logfile"
        done
    fi

    local -a files=()
    local nf t
    if [ "$scope_all" -eq 1 ]; then
        while IFS= read -r nf; do
            files+=("$nf")
        done < <(find /etc -type f -name '*.new' 2>/dev/null | sort)
    else
        while IFS= read -r nf; do
            t="${nf%.new}"
            if [ -n "${FULLID_OF_PATH[$t]:-}" ] || [ -n "${FULLID_OF_PATH[$nf]:-}" ]; then
                files+=("$nf")
                continue
            fi
            # Fallback for doinst.sh renames (e.g. rc.haproxy.edge -> rc.haproxy.new).
            # The package log records the shipped name, not the post-doinst name,
            # so the exact-path check above misses these.
            if [[ "$t" == /etc/* ]]; then
                for logged_path in "${!FULLID_OF_PATH[@]}"; do
                    case "$logged_path" in
                        "${t}.edge"|"${t}.ghostnet"|"${t}.sanctum")
                            files+=("$nf")
                            break
                            ;;
                    esac
                done
            fi
        done < <(find /etc -type f -name '*.new' 2>/dev/null | sort)
    fi

    [ ${#files[@]} -eq 0 ] && return 0

    if [ "$DRY_RUN" -eq 1 ] || [ ! -t 0 ] || [ ! -t 2 ]; then
        if [ "$DRY_RUN" -eq 1 ]; then
            warn "dry run: would prompt for ${#files[@]} .new config file(s):"
        else
            warn "note: ${#files[@]} .new config file(s) pending. Review manually:"
        fi
        for nf in "${files[@]}"; do log "  $nf"; done
        return 0
    fi

    local -a protected=(
        /etc/passwd /etc/passwd- /etc/shadow /etc/shadow-
        /etc/group  /etc/group-  /etc/gshadow /etc/gshadow-
        /etc/fstab
        /etc/rc.d/rc.inet1.conf
        /etc/ssh/sshd_config
        /etc/HOSTNAME
        /etc/hosts
        /etc/motd
        /etc/issue
    )
    local file target owner ans batch="" prot is_prot
    local total=${#files[@]} idx=0
    local old_sz new_sz old_mt new_mt

    header "${total} config file(s) have .new versions."

    for file in "${files[@]}"; do
        idx=$((idx + 1))
        target="${file%.new}"

        # 1. PROTECTED CHECK (Moved to the top so batch mode doesn't ignore it)
        is_prot=0
        for prot in "${protected[@]}"; do
            [ "$prot" = "$target" ] && { is_prot=1; break; }
        done
        if [ "$is_prot" -eq 1 ]; then
            log ""
            warn "[$idx/$total] $target [MANUAL MERGE REQUIRED]"
            log "    existing: $target"
            log "    new:      $file"
            continue
        fi

        # 2. BATCH MODE (Now safely processes everything else)
        if [ -n "$batch" ]; then
            case "$batch" in
                K) 
                    if [ ! -e "$target" ]; then
                        warn "Warning: Deleting new config for a non-existent file: $target"
                    fi
                    rm -f "$file" ;;
                R) 
                    if [ -e "$target" ]; then
                        cp -a "$target" "${target}.bak"
                    fi
                    mv -f "$file" "$target" ;;
            esac
            continue
        fi

        # 3. STANDARD UI
        new_sz=$(stat -c %s "$file"   2>/dev/null || echo "?")
        new_mt=$(date -r "$file"   '+%Y-%m-%d' 2>/dev/null || echo "?")

        if [ -e "$target" ] || [ -L "$target" ]; then
            old_sz=$(stat -c %s "$target" 2>/dev/null || echo "?")
            old_mt=$(date -r "$target" '+%Y-%m-%d' 2>/dev/null || echo "?")
        else
            old_sz="?"
            old_mt="?"
        fi

        owner="${FULLID_OF_PATH[$target]:-}"
        if [ -z "$owner" ]; then
            owner="${FULLID_OF_PATH[$file]:-}"
        fi
        if [ -z "$owner" ]; then
            owner="(no package log entry, orphaned .new file)"
        fi

        log ""
        info "[$idx/$total] $target"
        log "    package:  $owner"
        if [ "$old_sz" = "?" ]; then
            log "    existing: ${C_YELLOW}(file does not exist)${C_RESET}"
        else
            log "    existing: $old_sz bytes (modified $old_mt)"
        fi
        log "    new:      $new_sz bytes (modified $new_mt)"

        while true; do
            printf '\n  [k]eep old   [r]eplace   [d]iff   [s]kip   [q]uit\n' >&2
            printf '  batch:  [K]eep all remaining   [R]eplace all remaining\n' >&2
            printf '  choice > ' >&2
            read -r ans || return 0
            case "$ans" in
                k)    rm -f "$file"; break ;;
                r)    [ -f "$target" ] && cp -a "$target" "${target}.bak"
                      mv -f "$file" "$target"; break ;;
                d|D)  if [ -e "$target" ]; then
                          diff -u "$target" "$file" 2>&1 | head -n 80 >&2 || true
                      else
                          diff -u /dev/null "$file" 2>&1 | head -n 80 >&2 || true
                      fi ;;
                s|S)  break ;;
                K)    
                    if [ ! -e "$target" ]; then
                        warn "Warning: Deleting new config for a non-existent file: $target"
                    fi
                    batch=K; rm -f "$file"; break ;;
                R)    batch=R; [ -f "$target" ] && cp -a "$target" "${target}.bak"
                      mv -f "$file" "$target"; break ;;
                q|Q)  return 0 ;;
            esac
        done
    done
}

ensure_netmode() {
    local status current_mode remaining threshold
    
    # Query current netmode status (fallback to strict if it fails)
    status=$(netmode status 2>/dev/null || echo "mode=strict")
    current_mode=$(echo "$status" | awk -F= '/^mode=/ {print $2}')
    remaining=$(echo "$status" | awk -F= '/^remaining=/ {print $2}')
    
    # Ensure remaining is a valid integer
    [ -z "$remaining" ] && remaining=0
    [[ "$remaining" =~ ^[0-9]+$ ]] || remaining=0
    
    # Renew when remaining time drops below 50% of the timer (min 300s/5mins)
    threshold=$(( NETMODE_TIMER / 2 ))
    [ "$threshold" -lt 300 ] && threshold=300

    if [ "$current_mode" = "$AMOS_NETMODE" ] && [ "$remaining" -gt "$threshold" ]; then
        debug "netmode already active ($current_mode, ${remaining}s left, threshold=${threshold}s)"
        return 0
    fi
    
    netmode "$AMOS_NETMODE" "$NETMODE_TIMER"
}

download_and_install() {
    local -a pkglist=("$@")
    local pkg relpath dest md5 asc ok attempt n_pkgs=${#pkglist[@]}
    local n_cached=0 n_fetched=0 n_installed=0 n_skipped_inst=0
    local outfile rc out remaining got b idx=0

    mkdir -p "$TMP_ROOT"

    if [ -s "$CACHE_DIR/$GPG_KEY_NAME" ]; then
        check_key_pin "$CACHE_DIR/$GPG_KEY_NAME" require-pin \
            || die "GPG key pin check failed; refusing to trust signatures"
        gpg --import "$CACHE_DIR/$GPG_KEY_NAME" >/dev/null 2>&1 || true
    fi

    header "Pre-flight: validating plan for $n_pkgs package(s)"
    local -a bad=()
    for pkg in "${pkglist[@]}"; do
        relpath=$(relpath_of "$pkg")
        md5=$(md5_of "$pkg")
        [ -n "$relpath" ] || bad+=("$pkg (no relpath in index)")
        [ -n "$md5" ]     || bad+=("$pkg (no md5 in index)")
        log "  - $pkg"
    done
    if [ ${#bad[@]} -gt 0 ]; then
        for b in "${bad[@]}"; do
            error "plan invalid: $b"
        done
        die "plan validation failed (${#bad[@]} issue(s)); nothing downloaded, nothing changed"
    fi

    ensure_netmode
    header "Download phase: $n_pkgs package(s) (netmode: $AMOS_NETMODE)"
    
    idx=0
    for pkg in "${pkglist[@]}"; do
        idx=$((idx+1))
        ensure_netmode
        relpath=$(relpath_of "$pkg")
        md5=$(md5_of "$pkg")
        dest="$TMP_ROOT/$relpath"
        asc="${dest}.asc"
        mkdir -p "$(dirname "$dest")"

        if [ -f "$dest" ] && verify_md5 "$dest" "$md5" 2>/dev/null; then
            if [ -f "$asc" ] && verify_gpg "$dest" "$asc" 2>/dev/null; then
                info "[$idx/$n_pkgs] cached: $(basename "$dest")"
                n_cached=$((n_cached+1))
                continue
            elif [ -f "$asc" ]; then
                warn "[$idx/$n_pkgs] cached signature invalid for $pkg; re-downloading"
                rm -f "$dest" "$asc"
            else
                if fetch_file "${relpath}.asc" "$asc"; then
                    if ! verify_gpg "$dest" "$asc"; then
                        warn "[$idx/$n_pkgs] signature fetched but invalid for $pkg; re-downloading both"
                        rm -f "$dest" "$asc"
                    else
                        info "[$idx/$n_pkgs] cached (signature re-fetched): $(basename "$dest")"
                        n_cached=$((n_cached+1))
                        continue
                    fi
                else
                    warn "[$idx/$n_pkgs] no signature available for cached $pkg"
                    rm -f "$asc"
                    n_cached=$((n_cached+1))
                    continue
                fi
            fi
        fi

        # Cache is bad
        # Wipe both the package and the signature to prevent wget --continue
        # from reusing a stale signature from an older build of this package.
        rm -f "$dest" "$asc"
        
        ok=0
        for attempt in 1 2 3; do
            log "fetch $relpath"
            if fetch_file "$relpath" "$dest"; then
                if verify_md5 "$dest" "$md5"; then
                    ok=1
                    break
                else
                    got=$(md5sum "$dest" | awk '{print $1}')
                    FETCH_ERROR="MD5 mismatch: expected $md5, got $got"
                    log "MD5 mismatch for $pkg, retrying"
                    # Wipe both again in case the partial download was bad
                    rm -f "$dest" "$asc"
                fi
            fi
        done
        [ "$ok" -eq 1 ] || die "failed to obtain a good copy of $pkg: ${FETCH_ERROR:-unknown error}"

        if fetch_file "${relpath}.asc" "$asc"; then
            if ! verify_gpg "$dest" "$asc"; then
                die "GPG verification failed for $pkg ($relpath)"
            fi
            debug "signature OK: $pkg"
        else
            rm -f "$asc"
            die "no signature for $pkg"
        fi

        n_fetched=$((n_fetched+1))
        purge_stale_cache "$pkg" "$dest" "$asc"
    done
    netmode strict
    success "All $n_pkgs package(s) present and verified (cached: $n_cached, fetched: $n_fetched)"

    header "Install phase: committing changes now"

    # IMA Safeguard
    if ! command -v evmctl >/dev/null 2>&1; then
        die "IMA Key Safeguard: evmctl is missing (install ima-evm-utils from the z series). Aborting."
    fi
    if [ ! -r "/etc/keys/x509_ima.der" ]; then
        die "IMA Key Safeguard: /etc/keys/x509_ima.der is missing. Cannot verify signatures. Aborting."
    fi

    test_elf=""
    tmp_check=""
    for test_pkg in "${pkglist[@]}"; do
        test_pkg_path="$TMP_ROOT/$(relpath_of "$test_pkg")"
        [ -f "$test_pkg_path" ] || continue

        tmp_check=$(mktemp -d)
        tar --xattrs --xattrs-include='security.*' -xf "$test_pkg_path" -C "$tmp_check" 2>/dev/null || { rm -rf "$tmp_check"; tmp_check=""; continue; }

        while IFS= read -r -d '' f; do
            magic=$(head -c4 -- "$f" 2>/dev/null | od -An -tx1 | tr -d ' \n')
            if [ "$magic" = "7f454c46" ]; then
                test_elf="$f"
                break
            fi
        done < <(find "$tmp_check" -type f -print0)

        if [ -n "$test_elf" ]; then
            break
        fi
        rm -rf "$tmp_check"
        tmp_check=""
    done

    if [ -n "$test_elf" ]; then
        if ! evmctl ima_verify -k /etc/keys/x509_ima.der "$test_elf" >/dev/null 2>&1; then
            rm -rf "$tmp_check"
            header "IMA KEY MISMATCH"
            warn "The packages in the repository are signed with a different"
            warn "IMA key than the one currently trusted by the running kernel,"
            warn "or they lack valid IMA signatures."
            warn ""
            warn "Installing these packages will cause the kernel to block"
            warn "execution of the new binaries, locking up the system."
            warn ""
            info "To safely perform this upgrade, you must temporarily"
            info "disable IMA appraisal:"
            info "  1. Edit your bootloader configuration:"
            info "     - UEFI (ELILO): /boot/efi/EFI/AMOS/elilo.conf"
            info "     - BIOS (LILO):  /etc/lilo.conf"
            info "  2. Change 'ima_appraise=enforce' to 'ima_appraise=off'"
            info "  3. Reboot the system."
            info "  4. Run: amos full-upgrade"
            info "  5. Change it back to 'ima_appraise=enforce' and reboot again."
            die "Upgrade aborted to prevent system lockup."
        fi
    fi
    [ -n "$tmp_check" ] && rm -rf "$tmp_check"

    outfile="$(mktemp)"
    idx=0
    for pkg in "${pkglist[@]}"; do
        idx=$((idx+1))
        relpath=$(relpath_of "$pkg")
        dest="$TMP_ROOT/$relpath"
        if [ ! -f "$dest" ]; then
            warn "[$idx/$n_pkgs] not staged (skipping): $pkg"
            n_skipped_inst=$((n_skipped_inst+1))
            continue
        fi
        info "[$idx/$n_pkgs] Installing $(basename "$dest")"

        : > "$outfile"
        rc=0
        if [ "$REINSTALL" -eq 1 ]; then
            upgradepkg --reinstall --install-new "$dest" 2>&1 | tee "$outfile" || rc=$?
        else
            upgradepkg --install-new "$dest" 2>&1 | tee "$outfile" || rc=$?
        fi

        if [ "$rc" -ne 0 ]; then
            warn "upgradepkg rc=$rc for $pkg; falling back to installpkg"
            : > "$outfile"
            rc=0
            installpkg "$dest" 2>&1 | tee "$outfile" || rc=$?
        fi

        if [ "$rc" -ne 0 ]; then
            rm -f "$outfile"
            remaining=$(( n_pkgs - n_installed - n_skipped_inst - 1 ))
            header "INSTALL FAILURE"
            error "failed package:      $pkg"
            log "  installed before:    $n_installed"
            log "  skipped (already):   $n_skipped_inst"
            log "  not yet attempted:   $remaining"
            log ""
            info "Staged, verified downloads are preserved in:"
            log "    $TMP_ROOT"
            log ""
            info "To recover:"
            log "    1. Re-run:    amos upgrade --reinstall $pkg"
            log "       (verified downloads will be re-used, not re-fetched)"
            log "    2. Check:     ls -1 /var/log/packages/ | tail -20"
            log "    3. If in doubt about system state, reinstall the full plan:"
            log "       amos install --reinstall ${pkglist[*]}"
            die "install failed for $pkg"
        fi

        if grep -q 'Skipping package' "$outfile"; then
            debug "skipped (upgradepkg reported already installed)"
            n_skipped_inst=$((n_skipped_inst+1))
        else
            n_installed=$((n_installed+1))
        fi
    done
    rm -f "$outfile"

    # Unify system state and enforce Edge stripping
    if [ -x /usr/sbin/amos-harden ]; then
        header "Running system hardening (amos-harden)"
        # We don't pass --no-strip, because amos-harden will respect edge-keep.conf
        /usr/sbin/amos-harden --apply >/var/log/amos-harden.log 2>&1 || warn "amos-harden reported an error. Check /var/log/amos-harden.log"
    fi

    header "Post-transaction review (${#pkglist[@]} package(s) upgraded)"
    case "${POST_INSTALL_REVIEW:-scoped}" in
        scoped) review_new_configs -- "${pkglist[@]}" ;;
        all)    review_new_configs --all ;;
        *)      ;;
    esac

    if [ -f /run/amos-lilo-failed ]; then
        header "LILO REFRESH FAILED"
        warn "The kernel was upgraded but 'lilo' failed to write the MBR."
        warn "The machine will boot the OLD kernel or fail to boot."
        warn ""
        info "Run before rebooting:"
        log "     lilo"
        warn ""
        info "Details:"
        log "     /run/amos-lilo-failed"
        rm -f /run/amos-lilo-failed
    fi

    success "installed: $n_installed  skipped: $n_skipped_inst"
    info "verified downloads cached in $TMP_ROOT (re-used on next run)"
}

# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
cmd_clean() {
    [ -d "$TMP_ROOT" ] || { info "cache directory does not exist: $TMP_ROOT"; return 0; }

    local -A keepset=()
    local name fullid series relpath md5
    local keep_pkgs=0
    
    if [ "$HARD_CLEAN" -eq 0 ]; then
        local idx="$CACHE_DIR/packages.idx"
        [ -s "$idx" ] || die "no package index; run 'amos update' first (or use --hard to ignore the index)"
        
        while IFS='|' read -r name fullid series relpath md5; do
            [ -n "$relpath" ] || continue
            keepset["$TMP_ROOT/$relpath"]=1
            keepset["$TMP_ROOT/$relpath.asc"]=1
            keep_pkgs=$((keep_pkgs+1))
        done < "$idx"
    fi

    local -a stale=()
    local n_kept=0 f
    while IFS= read -r -d '' f; do
        if [ -n "${keepset[$f]:-}" ]; then
            n_kept=$((n_kept+1))
        else
            stale+=("$f")
        fi
    done < <(find "$TMP_ROOT" -type f -print0 2>/dev/null)

    if [ ${#stale[@]} -eq 0 ]; then
        if [ "$HARD_CLEAN" -eq 1 ]; then
            success "cache is completely empty"
        else
            success "cache is clean ($n_kept file(s) retained for packages in the current repo, nothing to remove)"
        fi
        return 0
    fi

    local total_bytes=0 sz
    for f in "${stale[@]}"; do
        sz=$(stat -c %s "$f" 2>/dev/null || echo 0)
        total_bytes=$((total_bytes + sz))
    done
    local total_human
    total_human=$(numfmt --to=iec "$total_bytes" 2>/dev/null || printf '%s B' "$total_bytes")

    if [ "$DRY_RUN" -eq 1 ]; then
        warn "dry run: would remove ${#stale[@]} file(s), $total_human from $TMP_ROOT"
        for f in "${stale[@]}"; do
            printf '  %s\n' "${f#$TMP_ROOT/}" >&2
        done
        if [ "$HARD_CLEAN" -eq 0 ]; then
            info "dry run: would retain $n_kept file(s) matching the current repo index"
        fi
        return 0
    fi

    info "removing ${#stale[@]} file(s), $total_human"
    for f in "${stale[@]}"; do
        rm -f "$f"
        debug "removed $f"
    done

    find "$TMP_ROOT" -mindepth 1 -type d -empty -delete 2>/dev/null || true

    if [ "$HARD_CLEAN" -eq 1 ]; then
        success "cache wiped completely ($total_human freed)"
    else
        success "cache cleaned; $n_kept file(s) retained ($total_human freed)"
    fi
}

check_toolchain_drift() {
    local -a user_targets=("$@")
    local e mid inst inst_base repo_base user_targeted t

    for e in "${ESSENTIAL_PKGS[@]}"; do
        mid=$(fullid_of "$e")
        inst=$(installed_fullid "$e")
        
        if [ -n "$mid" ] && [ -n "$inst" ] && [ "$inst" != "$mid" ]; then
            inst_base="${inst%-*-*}"
            repo_base="${mid%-*-*}"
            
            if [ "$inst_base" != "$repo_base" ]; then
                user_targeted=0
                for t in "${user_targets[@]}"; do
                    if [ "$t" = "$e" ]; then
                        user_targeted=1
                        break
                    fi
                done
                
                if [ "$user_targeted" -eq 0 ]; then
                    die "Repository toolchain ($e) has a version bump ($inst_base -> $repo_base). You must run 'amos full-upgrade' to safely upgrade the system."
                fi
            else
                debug "Allowing $e rebuild ($inst -> $mid) as a dependency."
            fi
        fi
    done
}

cmd_update() {
    load_mirrors

    info "updating from mirrors... (netmode: $AMOS_NETMODE)"
    netmode "$AMOS_NETMODE" "$NETMODE_TIMER"

    if fetch_file "$GPG_KEY_NAME" "$CACHE_DIR/$GPG_KEY_NAME"; then
        check_key_pin "$CACHE_DIR/$GPG_KEY_NAME" allow-create \
            || die "GPG key pin check failed; refusing to proceed"
        gpg --import "$CACHE_DIR/$GPG_KEY_NAME" >/dev/null 2>&1 || true
    else
        warn "could not fetch $GPG_KEY_NAME: $FETCH_ERROR"
        warn "CHECKSUMS.md5.asc cannot be verified without the key"
    fi

    fetch_file "$DEPS_NAME" "$CACHE_DIR/$DEPS_NAME" \
        || die "failed to fetch $DEPS_NAME: $FETCH_ERROR"

    local cs="$CACHE_DIR/$CHECKSUMS_NAME"
    local cs_tmp="$cs.tmp"
    local cs_asc="$cs.asc"
    local cs_asc_tmp="$cs_asc.tmp"

    fetch_file "$SERIES_ROOT/$CHECKSUMS_NAME" "$cs_tmp" \
        || { rm -f "$cs_tmp"; die "failed to fetch $CHECKSUMS_NAME: $FETCH_ERROR"; }

    if fetch_file "$SERIES_ROOT/$CHECKSUMS_NAME.asc" "$cs_asc_tmp" 2>/dev/null; then
        if gpg --verify "$cs_asc_tmp" "$cs_tmp" >/dev/null 2>&1; then
            debug "CHECKSUMS.md5 signature OK"
            mv "$cs_tmp" "$cs"
            mv "$cs_asc_tmp" "$cs_asc"
        else
            rm -f "$cs_tmp" "$cs_asc_tmp"
            die "CHECKSUMS.md5 signature verification FAILED; refusing to use index"
        fi
    else
        warn "no signature for $CHECKSUMS_NAME (${FETCH_ERROR:-fetch failed})"
        warn "index is unverified; packages will still be MD5+GPG checked individually"
        mv "$cs_tmp" "$cs"
        rm -f "$cs_asc_tmp"
    fi
    if [ "${SUPPRESS_NETMODE_STRICT:-0}" -eq 0 ]; then
        netmode strict
    fi
    build_index
    success "update complete"
}

run_impact_check() {
    local -a pkgs=("$@")
    [ "$CHECK_IMPACT" -eq 1 ] || return 0
    
    header "Dependency Impact Assessment"
    for p in "${pkgs[@]}"; do
        if [ -x /usr/sbin/needswhat ]; then
            info "Forward dependencies for $p:"
            /usr/sbin/needswhat "$p" || warn "needswhat failed for $p"
            log ""
        else
            warn "/usr/sbin/needswhat not found or not executable. Skipping forward deps."
        fi
        
        if [ -x /usr/sbin/whoneeds ]; then
            info "Reverse dependencies for $p (packages that require it):"
            /usr/sbin/whoneeds "$p" || warn "whoneeds failed for $p"
            log ""
        else
            warn "/usr/sbin/whoneeds not found or not executable. Skipping reverse deps."
        fi
    done
}

cmd_deps() {
    [ $# -eq 1 ] || die "usage: amos deps PKG"
    local pkg="$1"
    if [ -x /usr/sbin/needswhat ]; then
        /usr/sbin/needswhat "$pkg"
    else
        die "/usr/sbin/needswhat is not executable or missing."
    fi
}

cmd_rdeps() {
    [ $# -eq 1 ] || die "usage: amos rdeps PKG"
    local pkg="$1"
    if [ -x /usr/sbin/whoneeds ]; then
        /usr/sbin/whoneeds "$pkg"
    else
        die "/usr/sbin/whoneeds is not executable or missing."
    fi
}

cmd_install() {
    [ $# -ge 1 ] || die "usage: amos install [--dry-run] [--reinstall] PKG..."
    load_mirrors
    SUPPRESS_NETMODE_STRICT=1
    [ "$NO_AUTO_UPDATE" -eq 0 ] && cmd_update
    SUPPRESS_NETMODE_STRICT=0
    load_deps
    load_blacklist
    local -a raw_targets=("$@")
    local -a user_targets=() 
    local raw_p pkg_name
    for raw_p in "${raw_targets[@]}"; do
        pkg_name=$(resolve_pkg_name "$raw_p")
        if [ -z "$pkg_name" ]; then
            die "package not in repo index: $raw_p"
        fi
        user_targets+=("$pkg_name")
    done
    check_toolchain_drift "${user_targets[@]}"

    local p mid t user_named
    for p in "${user_targets[@]}"; do
        [ -n "$(fullid_of "$p")" ] || die "package not in repo index: $p"
        if is_blacklisted "$p"; then
            if [ "$FORCE_BLACKLIST" -eq 1 ]; then
                warn "$p is blacklisted but --force was given; proceeding"
            else
                die "package '$p' is in $BLACKLIST_FILE; refusing to install.
Remove it from $BLACKLIST_FILE, or use --force to override."
            fi
        fi
    done

    run_impact_check "${user_targets[@]}"

    local -a targets=()
    mapfile -t targets < <(direct_closure "${user_targets[@]}")

    maybe_note_ignored_edges "$IGNORED_EDGE_SRCS" "${targets[@]}"

    local -a todo=()
    local n_skip=0
    for p in "${targets[@]}"; do
        mid=$(fullid_of "$p")
        if [ -z "$mid" ]; then
            warn "dependency not in repo index: $p (skipped)"
            n_skip=$((n_skip+1))
            continue
        fi

        # 1. Check if the user explicitly named this package
        user_named=0
        for t in "${user_targets[@]}"; do
            [ "$t" = "$p" ] && { user_named=1; break; }
        done
        
        # 2. Essential package logic
        if is_essential "$p" && [ "$user_named" -eq 0 ]; then
            if needs_update "$p" "$mid"; then
                if is_blacklisted "$p"; then
                    if [ "$FORCE_BLACKLIST" -eq 1 ]; then
                        warn "essential package '$p' is blacklisted but --force was given; including rebuild"
                    else
                        die "cannot install: essential package '$p' needs rebuild but is in $BLACKLIST_FILE.
Remove '$p' from $BLACKLIST_FILE or use --force to override."
                    fi
                fi
                debug "including essential package rebuild $p"
                todo+=("$p")
            else
                debug "skipping essential package $p (transitive dep, up to date)"
                n_skip=$((n_skip+1))
            fi
            continue
        fi

        # 3. Reinstall check (--reinstall only applies to user_named)
        if [ "$REINSTALL" -eq 1 ]; then
            if [ "$user_named" -eq 0 ] && ! needs_update "$p" "$mid"; then
                n_skip=$((n_skip+1))
                continue
            fi
        elif ! needs_update "$p" "$mid"; then
            n_skip=$((n_skip+1))
            continue
        fi

        # 4. Blacklist check for transitive dependencies
        if is_blacklisted "$p" && [ "$user_named" -eq 0 ]; then
            if [ "$FORCE_BLACKLIST" -eq 1 ]; then
                warn "transitive dependency '$p' is blacklisted but --force was given; including it"
            else
                die "cannot install: '$p' is required transitively but is in $BLACKLIST_FILE.
Options:
  - remove '$p' from $BLACKLIST_FILE
  - install it explicitly with --force:  amos install --force $p
  - force this command:  amos install --force ${user_targets[*]}"
            fi
        fi

        todo+=("$p")
    done

    if [ ${#todo[@]} -eq 0 ]; then
        success "nothing to install (all ${#targets[@]} packages up to date)"
        return 0
    fi

    local -a ordered=()
    mapfile -t ordered < <(topo_sort "${todo[@]}")

    if [ "$DRY_RUN" -eq 1 ]; then
        print_plan "install" "targets" "${#targets[@]}" "$n_skip" "${ordered[@]}"
        return 0
    fi
    
    # If we are on Edge, explicitly requested packages should be kept.
    if [ "$(cat /etc/amos/edition 2>/dev/null)" = "edge" ]; then
        for p in "${user_targets[@]}"; do
            # Check if it's already in the file
            if ! grep -qxF "$p" /etc/amos/edge-keep.conf 2>/dev/null; then
                echo "$p" >> /etc/amos/edge-keep.conf
                info "Added explicitly installed package '$p' to edge-keep.conf"
            fi
        done
        chmod 600 /etc/amos/edge-keep.conf
    fi

    download_and_install "${ordered[@]}"
}

cmd_upgrade() {
    [ $# -ge 1 ] || die "usage: amos upgrade [--dry-run] [--reinstall] PKG..."
    load_mirrors
    SUPPRESS_NETMODE_STRICT=1
    [ "$NO_AUTO_UPDATE" -eq 0 ] && cmd_update
    SUPPRESS_NETMODE_STRICT=0
    load_deps
    load_blacklist
    local -a raw_targets=("$@")
    local -a user_targets=()
    local raw_p pkg_name
    for raw_p in "${raw_targets[@]}"; do
        pkg_name=$(resolve_pkg_name "$raw_p")
        if [ -z "$pkg_name" ]; then
            die "package not in repo index: $raw_p"
        fi
        user_targets+=("$pkg_name")
    done
    check_toolchain_drift "${user_targets[@]}"
    local -a installed_targets=()
    local p mid inst t user_named
    for p in "${user_targets[@]}"; do
        [ -n "$(fullid_of "$p")" ] || die "package not in repo index: $p"
        if is_blacklisted "$p"; then
            if [ "$FORCE_BLACKLIST" -eq 1 ]; then
                warn "$p is blacklisted but --force was given; proceeding"
            else
                die "package '$p' is in $BLACKLIST_FILE; refusing to upgrade.
Remove it from $BLACKLIST_FILE, or use --force to override."
            fi
        fi
        inst=$(installed_fullid "$p")
        if [ -z "$inst" ]; then
            warn "$p is not installed (use 'amos install $p' if you meant to install it)"
            continue
        fi
        installed_targets+=("$p")
    done

    if [ ${#installed_targets[@]} -eq 0 ]; then
        success "nothing to upgrade"
        return 0
    fi

    run_impact_check "${installed_targets[@]}"

    # 1. Get reverse dependencies (what depends on our targets)
    local -a rev_deps=()
    mapfile -t rev_deps < <(reverse_closure "${installed_targets[@]}")
    
    # 2. Get direct dependencies (what our targets depend on)
    local -a dir_deps=()
    mapfile -t dir_deps < <(direct_closure "${installed_targets[@]}")
    
    # 3. Create a map to remember which packages are reverse dependencies
    local -A REV_MAP=()
    for p in "${rev_deps[@]}"; do
        REV_MAP[$p]=1
    done

    # 4. Combine and deduplicate
    local -a targets=()
    mapfile -t targets < <(printf '%s\n' "${rev_deps[@]}" "${dir_deps[@]}" | sort -u)

    maybe_note_ignored_edges "$IGNORED_EDGE_DSTS" "${targets[@]}"
    local -a todo=()
    local n_skip=0
    for p in "${targets[@]}"; do
        mid=$(fullid_of "$p")
        if [ -z "$mid" ]; then
            warn "package not in repo index: $p (skipped)"
            n_skip=$((n_skip+1))
            continue
        fi
        inst=$(installed_fullid "$p")
        
        if [ -z "$inst" ]; then
            # If it's a reverse dependency but it's not installed, skip it.
            # We only upgrade reverse deps that are actually on the system.
            if [ -n "${REV_MAP[$p]:-}" ]; then
                n_skip=$((n_skip+1))
                continue
            fi
            
            # If it's a missing FORWARD dependency, we can safely install it.
            user_named=0
            for t in "${user_targets[@]}"; do
                [ "$t" = "$p" ] && { user_named=1; break; }
            done
            
            if is_blacklisted "$p" && [ "$user_named" -eq 0 ]; then
                warn "skipping blacklisted missing dependency: $p"
                n_skip=$((n_skip+1))
                continue
            fi
            todo+=("$p")
            continue
        fi

        user_named=0
        for t in "${user_targets[@]}"; do
            [ "$t" = "$p" ] && { user_named=1; break; }
        done

        if [ "$REINSTALL" -eq 1 ]; then
            if [ "$user_named" -eq 0 ] && ! needs_update "$p" "$mid"; then
                n_skip=$((n_skip+1))
                continue
            fi
        elif ! needs_update "$p" "$mid"; then
            n_skip=$((n_skip+1))
            continue
        fi

        if is_blacklisted "$p" && [ "$user_named" -eq 0 ]; then
            warn "skipping blacklisted reverse-dependency: $p"
            n_skip=$((n_skip+1))
            continue
        fi

        todo+=("$p")
    done

    if [ ${#todo[@]} -eq 0 ]; then
        success "nothing to upgrade"
        return 0
    fi

    local -a ordered=()
    mapfile -t ordered < <(topo_sort "${todo[@]}")

    if [ "$DRY_RUN" -eq 1 ]; then
        print_plan "upgrade" "closure" "${#targets[@]}" "$n_skip" "${ordered[@]}"
        return 0
    fi

    download_and_install "${ordered[@]}"
}

cmd_upgrade_all() {
    load_mirrors
    SUPPRESS_NETMODE_STRICT=1
    [ "$NO_AUTO_UPDATE" -eq 0 ] && cmd_update
    SUPPRESS_NETMODE_STRICT=0
    load_deps
    load_blacklist
    local idx="$CACHE_DIR/packages.idx"
    [ -s "$idx" ] || die "no package index; run 'amos update'"

    local -a todo=()
    local -a essential_pending=()
    local name fullid series relpath md5 inst inst_base repo_base
    local n_index=0 n_installed=0 n_current=0 blacklisted_count=0
    
    while IFS='|' read -r name fullid series relpath md5; do
        n_index=$((n_index+1))
        inst=$(installed_fullid "$name")
        [ -n "$inst" ] || continue
        n_installed=$((n_installed+1))
        
        if [ "$REINSTALL" -ne 1 ] && ! needs_update "$name" "$fullid"; then
            n_current=$((n_current+1))
            continue
        fi

        if is_essential "$name"; then
            inst_base="${inst%-*-*}"
            repo_base="${fullid%-*-*}"
            if [ "$inst_base" != "$repo_base" ]; then
                essential_pending+=("$name")
                continue
            fi
        fi

        if is_blacklisted "$name"; then
            if [ "$FORCE_BLACKLIST" -eq 1 ]; then
                warn "$name is blacklisted but --force was given; including it"
            else
                blacklisted_count=$((blacklisted_count+1))
                continue
            fi
        fi

        todo+=("$name")
    done < "$idx"

    if [ ${#essential_pending[@]} -gt 0 ]; then
        header "TOOLCHAIN VERSION DRIFT"
        warn "The repository's core toolchain has a new version:"
        for p in "${essential_pending[@]}"; do
            log "    $p (installed: $(installed_fullid "$p") | repo: $(fullid_of "$p"))"
        done
        warn ""
        warn "You cannot run 'upgrade-all' because the remaining packages in"
        warn "the repository were compiled against this newer toolchain and"
        warn "will crash if installed against the old one."
        warn ""
        info "To upgrade safely, run: amos full-upgrade"
        die "Toolchain version drift detected. Upgrade aborted."
    fi

    [ "$blacklisted_count" -gt 0 ] && \
        warn "note: $blacklisted_count package(s) skipped by $BLACKLIST_FILE"

    if [ ${#todo[@]} -eq 0 ]; then
        success "system is up to date ($n_installed installed, $n_index in repo)"
        return 0
    fi

    local -a ordered=()
    mapfile -t ordered < <(topo_sort "${todo[@]}")

    if [ "$DRY_RUN" -eq 1 ]; then
        print_plan "upgrade" "installed" "$n_installed" "$n_current" "${ordered[@]}"
        return 0
    fi

    POST_INSTALL_REVIEW=all
    download_and_install "${ordered[@]}"
}

cmd_full_upgrade() {
    load_mirrors
    SUPPRESS_NETMODE_STRICT=1
    [ "$NO_AUTO_UPDATE" -eq 0 ] && cmd_update
    SUPPRESS_NETMODE_STRICT=0
    load_deps
    load_blacklist
    local idx="$CACHE_DIR/packages.idx"
    [ -s "$idx" ] || die "no package index; run 'amos update'"

    local e mid_e inst_e
    for e in "${ESSENTIAL_PKGS[@]}"; do
        is_blacklisted "$e" || continue
        mid_e=$(fullid_of "$e")
        inst_e=$(installed_fullid "$e")
        if [ -n "$mid_e" ] && [ -n "$inst_e" ] && [ "$inst_e" != "$mid_e" ]; then
            die "cannot run full-upgrade: essential package '$e' is in $BLACKLIST_FILE
but needs updating ($inst_e -> $mid_e).
Remove '$e' from $BLACKLIST_FILE before running full-upgrade."
        fi
    done

    local -a todo=()
    local name fullid series relpath md5 inst
    local blacklisted_count=0
    while IFS='|' read -r name fullid series relpath md5; do
        inst=$(installed_fullid "$name")
        [ -n "$inst" ] || continue
        if [ "$REINSTALL" -ne 1 ] && ! needs_update "$name" "$fullid"; then
            continue
        fi

        if is_blacklisted "$name"; then
            if [ "$FORCE_BLACKLIST" -eq 1 ]; then
                warn "$name is blacklisted but --force was given; including it"
            else
                blacklisted_count=$((blacklisted_count+1))
                continue
            fi
        fi

            todo+=("$name")
    done < "$idx"

    [ "$blacklisted_count" -gt 0 ] && \
        warn "note: $blacklisted_count package(s) skipped by $BLACKLIST_FILE"

    if [ ${#todo[@]} -eq 0 ]; then
        success "system is up to date"
        return 0
    fi

    PKG_PRIO_OVERRIDE=()
    for p in "${ESSENTIAL_PKGS[@]}"; do
        PKG_PRIO_OVERRIDE[$p]=-1000
    done
    for p in "${BOOTSTRAP_PKGS[@]}"; do
        PKG_PRIO_OVERRIDE[$p]=-500
    done

    local -a ordered=()
    mapfile -t ordered < <(topo_sort "${todo[@]}")

    PKG_PRIO_OVERRIDE=()

    if [ "$DRY_RUN" -eq 1 ]; then
        print_plan "full-upgrade" "installed" "${#todo[@]}" "0" "${ordered[@]}"
        return 0
    fi

    POST_INSTALL_REVIEW=all
    download_and_install "${ordered[@]}"
}

cmd_list() {
    local pat="${1:-}"
    local idx="$CACHE_DIR/packages.idx"
    [ -s "$idx" ] || die "no package index; run 'amos update'"
    if [ -z "$pat" ]; then
        awk -F'|' '{ printf "%-6s %s\n", $3, $2 }' "$idx" | sort -k2
    else
        awk -F'|' -v p="$pat" '$1 ~ p { printf "%-6s %s\n", $3, $2 }' "$idx" | sort -k2
    fi
}

cmd_configs() {
    review_new_configs --all
}

cmd_check() {
    load_deps
    local idx="$CACHE_DIR/packages.idx"
    [ -s "$idx" ] || die "no package index; run 'amos update'"

    local -A in_index=()
    local name fullid series relpath md5
    while IFS='|' read -r name fullid series relpath md5; do
        in_index[$name]=1
    done < "$idx"

    local errs=0 pkg d
    for pkg in "${!PKG_DEPS[@]}"; do
        if [ -z "${in_index[$pkg]:-}" ]; then
            error "missing in index: $pkg (referenced by deps.conf)"
            errs=$((errs+1))
        fi
        for d in ${PKG_DEPS[$pkg]}; do
            if [ -z "${PKG_DEPS[$d]+x}" ]; then
                error "missing dep: $pkg -> $d (not in deps.conf)"
                errs=$((errs+1))
            fi
        done
    done

    for name in "${!in_index[@]}"; do
        if [ -z "${PKG_DEPS[$name]+x}" ]; then
            debug "note: $name is in the index but not in deps.conf"
        fi
    done

    if [ "$errs" -eq 0 ]; then
        success "check: OK"
    else
        die "check: $errs problem(s)"
    fi
}

cmd_blacklist() {
    load_blacklist
    if [ ${#BLACKLIST[@]} -eq 0 ]; then
        info "no blacklist entries ($BLACKLIST_FILE missing or empty)"
        return 0
    fi
    info "$BLACKLIST_FILE: ${#BLACKLIST[@]} pattern(s)"
    local pat
    for pat in "${BLACKLIST[@]}"; do
        log "  $pat"
    done
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

ARGS=()
while [ $# -gt 0 ]; do
    case "$1" in
        -h|--help)   cmd_help; exit 0 ;;
        --dry-run)   DRY_RUN=1; shift ;;
        --reinstall) REINSTALL=1; shift ;;
        --check-impact) CHECK_IMPACT=1; shift ;;
        --force-key-rotate)  FORCE_KEY_ROTATE=1; shift ;;
        --force)     FORCE_BLACKLIST=1; shift ;;
        --netmode)   AMOS_NETMODE="$2"; shift 2 ;;
        --hard)      HARD_CLEAN=1; shift ;;
        --)          shift; ARGS+=("$@"); break ;;
        -*)          die "unknown option: $1 (try 'amos --help')" ;;
        *)           ARGS+=("$1"); shift ;;
    esac
done

case "$AMOS_NETMODE" in
    open|clearnet) ;;
    strict)
        die "AMOS_NETMODE=strict would block all downloads; use 'open' or 'clearnet'"
        ;;
    *)
        die "AMOS_NETMODE must be 'open' or 'clearnet' (got: $AMOS_NETMODE)"
        ;;
esac

[ ${#ARGS[@]} -ge 1 ] || { cmd_help >&2; exit 1; }

CMD="${ARGS[0]}"
POS=("${ARGS[@]:1}")

case "$CMD" in
    help)        cmd_help ;;
    update)      cmd_update ;;
    install)     cmd_install "${POS[@]}" ;;
    upgrade)     cmd_upgrade "${POS[@]}" ;;
    upgrade-all)  cmd_upgrade_all ;;
    full-upgrade) cmd_full_upgrade ;;
    clean)       cmd_clean ;;
    list)        cmd_list "${POS[@]}" ;;
    deps)        cmd_deps "${POS[@]}" ;;
    rdeps)       cmd_rdeps "${POS[@]}" ;;
    check)       cmd_check ;;
    blacklist)   cmd_blacklist ;;
    configs)     cmd_configs ;;
    *)           die "unknown command: $CMD (try 'amos --help')" ;;
esac