#!/bin/bash
#
set -o pipefail
unset CFLAGS CXXFLAGS SLKCFLAGS SLKLDFLAGS CPPFLAGS LDFLAGS MAKEFLAGS
# Configuration------------------
KSERIES="k72"
REPO_DIR="/repo"
SOURCE_DIR="$REPO_DIR/source"
PKG_DIR="$REPO_DIR/slackware64"
CUSTOM_OUTPUT="$REPO_DIR/amos64"
OVERRIDES_DIR="$REPO_DIR/overrides"
TMP=${TMP:-/tmp}
LOGDIR="$TMP/build_world"
mkdir -p "$LOGDIR"
OUTPUT_LOCATION="$TMP"
RETRY_LOG="$LOGDIR/retry.log"
#DEFAULT_JOBS_COUNT=$(( $(nproc) * 4 / 5 > 0 ? $(nproc) * 4 / 5 : 1 ))
DEFAULT_JOBS_COUNT=6
DEFAULT_JOBS_FLAG="-j $DEFAULT_JOBS_COUNT"

# Option parsing-----------------
BUILD_SERIES=""
SKIP_SERIES=""
SKIP_PACKAGES=""
BLACKLIST_FILE=""
ALLOWLIST_FILE=""
NOZ=1

# Helper functions---------------
die()  { echo "ERROR: $*" >&2; exit 1; }
info() { echo ">>> $*"; }
warn() { echo "!!! $*"; }

upgradepkg --reinstall "$CUSTOM_OUTPUT"/a/pkgtools-*.txz

# Verify the forked makepkg is actually installed before proceeding.
# If we use the stock makepkg, the entire build will silently lack IMA signatures.
if ! grep -q 'AM·OS: IMA-sign every executable, script, and shared library in the tree.' /sbin/makepkg; then
    die "ERROR: Stock makepkg detected. The forked pkgtools is missing from $CUSTOM_OUTPUT/a/."
fi


find $SOURCE_DIR -name slack-desc -exec sed -i 's/Slackware/AM·OS/g' {} +
find $SOURCE_DIR -name 'README*' -exec sed -i 's/Slackware/AM·OS/g' {} +

PRIORITY_BUILD=(
    "d/gcc/gcc.SlackBuild"
    "a/gawk/gawk.SlackBuild"
    "d/binutils/binutils.SlackBuild"
    "l/glibc/glibc.SlackBuild"
)

SERIAL_BUILD_PKGS=(groff)

# let the show on the road
compgen -G "$CUSTOM_OUTPUT/a/aaa_glibc-solibs-*.txz" > /dev/null && \
    mv $CUSTOM_OUTPUT/a/aaa_glibc-solibs-*.txz $CUSTOM_OUTPUT/l/
compgen -G "$CUSTOM_OUTPUT/a/ncurses-*.txz" > /dev/null && \
    mv $CUSTOM_OUTPUT/a/ncurses-*.txz $CUSTOM_OUTPUT/l/

export TMPDIR="/tmp"
/usr/sbin/update-ca-certificates --fresh

while [[ $# -gt 0 ]]; do
    case "$1" in
        --series) BUILD_SERIES="${2//,/ }" ; shift 2 ;;
        --skip-series) SKIP_SERIES="${2//,/ }" ; shift 2 ;;
        --skip-packages) SKIP_PACKAGES="${2//,/ }" ; shift 2 ;;
        --blacklist-file) BLACKLIST_FILE="$2" ; shift 2 ;;
        --allowlist-file) ALLOWLIST_FILE="$2" ; shift 2 ;;
        --noz) NOZ=1 ; shift ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--series a,ap] [--skip-series kde,xfce] [--skip-packages pkg1,pkg2] [--blacklist-file /path/to/blacklist.txt] [--allowlist-file /path/to/packages.list]"
            echo "Usage: $0 [--series a,ap] [--skip-series kde,xfce] [--skip-packages pkg1,pkg2] [--blacklist-file /path/to/blacklist.txt] [--allowlist-file /path/to/packages.list] [--noz]"
            exit 1
            ;;
    esac
done

# Default blacklist file (if not provided) -----------------------------
if [ -z "$BLACKLIST_FILE" ]; then
    SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
    DEFAULT_BLACKLIST="$SCRIPT_DIR/blacklist.txt"
    if [ -f "$DEFAULT_BLACKLIST" ]; then
        BLACKLIST_FILE="$DEFAULT_BLACKLIST"
    fi
fi

# Sanity checks------------------
[ -d "$SOURCE_DIR" ] || { echo "ERROR: source tree not found at $SOURCE_DIR. Are you inside the chroot?"; exit 1; }
shopt -s nullglob


# Sync BUILD= from upstream into an override ---------------------------
# Upstream is re-synced periodically and can bump the BUILD number in
#     BUILD=${BUILD:-N}
# Copying an override with a stale N over upstream would downgrade the
# package. Rewrite the override's N to match upstream's before the copy.
# Only touches .SlackBuild files. Silent no-op if either side has no match.
mkdir -p $SOURCE_DIR/a/kernel-firmware-edge
sync_override_build() {
    local override_file="$1"
    local source_file="$2"
    local rel="$3"

    case "$override_file" in
        *.SlackBuild) ;;
        *) return 0 ;;
    esac
    [ -f "$source_file" ] || return 0

    local up_num ov_num
    up_num=$(sed -n 's/^.*BUILD=${BUILD:-\([0-9]\+\)}.*$/\1/p' "$source_file" | head -n1)
    ov_num=$(sed -n 's/^.*BUILD=${BUILD:-\([0-9]\+\)}.*$/\1/p' "$override_file" | head -n1)

    [ -z "$up_num" ] && return 0
    [ -z "$ov_num" ] && return 0
    [ "$up_num" = "$ov_num" ] && return 0

    sed -i 's|BUILD=${BUILD:-[0-9]\+}|BUILD=${BUILD:-'"${up_num}"'}|' "$override_file"
    echo ">>>   synced BUILD in override: $rel (${ov_num} -> ${up_num})"
}
#------------------------------------
# Apply overrides
#------------------------------------
# Overrides live at /repo/overrides/<series>/... and mirror the source
# tree. Every entry, file or directory, is copied to the same relative
# path under $SOURCE_DIR. The only exclusion is files ending in
# .upstream, which are snapshots written by enter_chroot.sh.
#
# Rule: overrides never resurrect a package directory that the source
# tree does not already contain. They can modify an existing package
# (replace its SlackBuild, add a subdirectory, drop in a patch), but
# they cannot introduce a package that upstream or packages.list
# removed. This is enforced by classifying each top-level series dir
# under overrides/ as either:
#
#   flat       -- the series dir carries .SlackBuild files directly,
#                 so its entries map straight into source/<series>/.
#                 k72 is the canonical case: source/k72/ IS the series.
#                 Depth-2 entries under it are ordinary subdirectories
#                 (like patches-7.2.7/) and may be created.
#
#   structured -- the series dir carries package subdirectories, as
#                 ap/mariadb, l/glibc, n/openssl do. Depth-2 entries
#                 are package dirs. If source/<series>/<pkg> does not
#                 already exist, the override for that package is
#                 skipped in its entirety.
#
# No series name is hardcoded. Detection is by looking for .SlackBuild
# files at the top of each series dir in the override tree.

if [ -d "$OVERRIDES_DIR" ]; then
    echo ">>> Applying overrides from $OVERRIDES_DIR ..."
    override_count=0
    override_dirs=0
    override_missing=0

    declare -A FLAT_SERIES
    for sdir in "$OVERRIDES_DIR"/*/; do
        [ -d "$sdir" ] || continue
        s=$(basename "$sdir")
        if find "$sdir" -maxdepth 1 -name '*.SlackBuild' -print -quit 2>/dev/null | grep -q .; then
            FLAT_SERIES["$s"]=1
        fi
    done

    declare -A WARNED

    while IFS= read -r -d '' ob; do
        rel="${ob#$OVERRIDES_DIR/}"
        target="$SOURCE_DIR/$rel"
        tdir=$(dirname "$target")
        series="${rel%%/*}"

        # The series dir must already exist in source. This also covers
        # the flat-series case where the series dir IS the anchor.
        if [ ! -d "$SOURCE_DIR/$series" ]; then
            if [ -z "${WARNED[series:$series]:-}" ]; then
                echo "!!! Override series not in source: $SOURCE_DIR/$series (skipping)"
                WARNED["series:$series"]=1
            fi
            override_missing=$((override_missing + 1))
            continue
        fi

        # For structured series, the depth-2 directory is a package
        # and must already exist in source. Compute it for every
        # entry so files and subdirs under a missing package are
        # skipped too, not just the package dir itself.
        if [ -z "${FLAT_SERIES[$series]:-}" ]; then
            n=$(printf '%s' "$rel" | awk -F/ '{print NF}')
            if [ "$n" -ge 2 ]; then
                pkg_root=$(printf '%s' "$rel" | cut -d/ -f1,2)
                if [ ! -d "$SOURCE_DIR/$pkg_root" ]; then
                    if [ -z "${WARNED[pkg:$pkg_root]:-}" ]; then
                        echo "!!! Override package not in source: $SOURCE_DIR/$pkg_root (skipping)"
                        WARNED["pkg:$pkg_root"]=1
                    fi
                    override_missing=$((override_missing + 1))
                    continue
                fi
            fi
        fi

        # Defensive: the immediate parent must exist. For flat series
        # this is what lets subdirs of an existing series anchor be
        # created; for structured series the package check above
        # already ran.
        if [ ! -d "$tdir" ]; then
            echo "!!! Override target dir missing: $tdir (skipping $rel)"
            override_missing=$((override_missing + 1))
            continue
        fi

        if [ -d "$ob" ]; then
            mkdir -p "$target"
            echo ">>>   override dir: $rel/"
            override_dirs=$((override_dirs + 1))
        else
            sync_override_build "$ob" "$target" "$rel"
            cp -a "$ob" "$target"
            rm -f "$target.orig"
            echo ">>>   override: $rel"
            override_count=$((override_count + 1))
        fi
    done < <(find "$OVERRIDES_DIR" -mindepth 1 ! -name '*.upstream' -print0)

    echo ">>>   applied $override_count file(s) across $override_dirs dir(s), $override_missing skipped"
else
    echo ">>> No overrides directory at $OVERRIDES_DIR (nothing to apply)"
fi

#------------------------------------
# Pre-build check: doinst.sh consistency
#------------------------------------
# Some SlackBuilds reference doinst.sh.gz but only ship doinst.sh, or
# vice versa. Check before compiling anything.
# A broken SlackBuild aborts the run early instead of ending up with
# botched packages.
#
# Runs after the overrides pass so an override can supply the missing
# file (overrides/l/libcap-ng/doinst.sh.gz, for example) and clear the
# check without editing the upstream SlackBuild.
#
# Two patterns are flagged:
#
#   GZ-MISSING     SlackBuild references doinst.sh.gz but the file
#                  does not exist alongside it
#
#   UNCOMP-MISSING SlackBuild cats doinst.sh but only doinst.sh.gz
#                  exists (needs zcat / gunzip first)
#
# Both are fatal.

info "Checking doinst.sh consistency across $SOURCE_DIR..."

DOINST_BAD=0
while IFS= read -r -d '' sb; do
    d=$(dirname "$sb")
    rel="${sb#$SOURCE_DIR/}"

    # Strip full-line comments before matching. Trailing '#' is left
    # alone: a '# ' inside a quoted string would be a false negative,
    # and a real '# …doinst.sh…' after code is vanishingly rare.
    nc=$(sed '/^[[:space:]]*#/d' "$sb")

    # Pattern 1: mentions doinst.sh.gz but the file is absent.
    if printf '%s\n' "$nc" | grep -qE 'doinst\.sh\.gz' && [ ! -f "$d/doinst.sh.gz" ]; then
        warn "GZ-MISSING: $rel (references doinst.sh.gz, file absent)"
        DOINST_BAD=$((DOINST_BAD + 1))
    fi

    # Pattern 2: cat doinst.sh, only doinst.sh.gz exists. Anchored so
    # zcat and *.cat filenames do not false-positive.
    if printf '%s\n' "$nc" \
         | grep -qE '(^|[^.[:alnum:]_])cat[[:space:]].*doinst\.sh([^.[:alnum:]_]|$)' \
       && [ ! -f "$d/doinst.sh" ] && [ -f "$d/doinst.sh.gz" ]; then
        warn "UNCOMP-MISSING: $rel (cats doinst.sh, only .gz exists)"
        DOINST_BAD=$((DOINST_BAD + 1))
    fi
done < <(find "$SOURCE_DIR" -name '*.SlackBuild' -type f -print0)

if [ "$DOINST_BAD" -gt 0 ]; then
    die "$DOINST_BAD doinst.sh inconsistencies found. Fix the listed SlackBuilds or supply the missing files under $OVERRIDES_DIR/ before building."
fi

info "  doinst.sh check passed."

#------------------------------------
# Restore testing packages to $CUSTOM_OUTPUT
#------------------------------------
# The previous run moved TESTING_LIST packages into amos64-testing/.
# Move them back so the incremental build check and z-check see them.
# The end-of-run block re-parks them.

if [ -d "$REPO_DIR/amos64-testing" ]; then
    restored=0
    for tdir in "$REPO_DIR/amos64-testing"/*/; do
        [ -d "$tdir" ] || continue
        tseries=$(basename "$tdir")
        dest_series="$CUSTOM_OUTPUT/$tseries"
        mkdir -p "$dest_series"

        for tfile in "$tdir"*.t?z; do
            [ -f "$tfile" ] || continue
            tfilename=$(basename "$tfile")

            if mv -f "$tfile" "$dest_series/"; then
                info "  restored: $tseries/$tfilename"
                restored=$((restored + 1))
            else
                warn "  restore failed: $tfile"
                continue
            fi

            tbase_path="${tfile%.t?z}"
            [ -f "${tbase_path}.txt" ] && mv -f "${tbase_path}.txt" "$dest_series/"
            [ -f "${tfile}.asc"      ] && mv -f "${tfile}.asc"      "$dest_series/"
        done

        rmdir "$tdir" 2>/dev/null || true
    done

    [ "$restored" -gt 0 ] && info "Restored $restored package(s) from amos64-testing to $CUSTOM_OUTPUT."
fi


# IMA signing configuration------
# Every ELF object built by this script is signed with the IMA private key
# so that installpkg preserves the security.ima xattr and the kernel can
# appraise the result at runtime. Set IMA_SIGN=0 in the environment to
# build without signing.
IMA_SIGN="${IMA_SIGN:-1}"
IMA_KEY="${IMA_KEY:-/root/kernel-keys/ima-signing.pem}"
IMA_HASH="${IMA_HASH:-sha256}"

if [ "$IMA_SIGN" = "1" ]; then
    [ -r "$IMA_KEY" ] || die "IMA signing key not readable: $IMA_KEY (set IMA_SIGN=0 to build without signing)"
    command -v evmctl >/dev/null 2>&1 || die "evmctl not found in PATH; cannot sign packages (set IMA_SIGN=0 to build without signing)"
    export IMA_KEY IMA_HASH
    info "IMA signing enabled: key=$IMA_KEY hash=$IMA_HASH"
else
    unset IMA_KEY IMA_HASH
    info "IMA signing disabled (IMA_SIGN=0)"
fi



# Package sidecar helpers--------

# Copy the .txt package description next to a built .txz.
# Prefers the upstream file of the same name (fast, canonical);
# falls back to extracting install/slack-desc from the built
# package so a version/build mismatch never leaves a stale .txt.
write_txt_for() {
    local pkgfile="$1"        # full path to the built .txz / .tgz
    local series="$2"         # e.g. a, ap, d, ...
    local dest="$3"           # directory the .txt should land in
    [ -f "$pkgfile" ] || return 0

    local name base upstream_txt our_txt
    name=$(basename "$pkgfile")
    base="${name%.t?z}"
    upstream_txt="$PKG_DIR/$series/${base}.txt"
    our_txt="$dest/${base}.txt"

    if [ -f "$upstream_txt" ]; then
        cp -a "$upstream_txt" "$our_txt"
        return 0
    fi

    # Fallback: pull slack-desc out of the package itself.
    if tar -xOf "$pkgfile" install/slack-desc > "$our_txt.tmp" 2>/dev/null \
       && [ -s "$our_txt.tmp" ]; then
        mv "$our_txt.tmp" "$our_txt"
        chmod 644 "$our_txt"
        touch -r "$pkgfile" "$our_txt"
    else
        rm -f "$our_txt.tmp"
        warn "No upstream .txt and no extractable slack-desc for $name"
    fi
}



#------------------------------------
# 1a. Inject ANNE Media copyright into every SlackBuild
#------------------------------------
# Add a copyright line crediting ANNE Media above the first
# "# All rights reserved." line in each SlackBuild. The original authors'
# notices are preserved untouched; this only adds ours alongside theirs,
# which the combined/derived work warrants.
#
# Idempotent by content check: a file whose header already mentions
# "Copyright ... ANNE Media" is skipped. Year is dynamic (current
# calendar year at build time).
#
# A .orig backup is not written — this is a comment-only change, and the
# hardening pass (which does snapshot .orig) runs afterward and will pick
# up the already-injected version, so `find -name '*.SlackBuild.orig' |
# ... revert` still restores a clean original.

ANNE_YEAR=$(date +%Y)
ANNE_COPY="# Copyright ${ANNE_YEAR} ANNE Media"

info "Injecting ANNE Media copyright (${ANNE_YEAR}) into SlackBuilds..."

copyright_injected=0
copyright_skipped=0
copyright_nomatch=0

while IFS= read -r slackbuild; do
    if grep -q 'Copyright.*ANNE Media' "$slackbuild"; then
        copyright_skipped=$((copyright_skipped + 1))
        continue
    fi

    if ! grep -qE '^#[[:space:]]*All rights reserved\.' "$slackbuild"; then
        copyright_nomatch=$((copyright_nomatch + 1))
        continue
    fi

    # 0,/re/ anchors on the *first* "# All rights reserved." line, so a
    # stray second occurrence further down (unlikely in a .SlackBuild, but
    # possible in a vendored snippet) is left alone. The `&` in the
    # replacement preserves whatever exact spacing the original line had.
    sed -i "0,/^#[[:space:]]*All rights reserved\./s/^#[[:space:]]*All rights reserved\./${ANNE_COPY}\n&/" \
        "$slackbuild"

    copyright_injected=$((copyright_injected + 1))
    info "  + copyright: ${slackbuild#$SOURCE_DIR/}"
done < <(find "$SOURCE_DIR" -name '*.SlackBuild' -type f | sort)

info "Copyright injection summary: $copyright_injected added, $copyright_skipped already present, $copyright_nomatch without 'All rights reserved.'"

info "Patching NUMJOBS to use $DEFAULT_JOBS_FLAG CPU cores..."
NUMJOBS_MARKER="# CUSTOM_BUILD_NUMJOBS_PATCHED"

while IFS= read -r slackbuild; do
    grep -q "$NUMJOBS_MARKER" "$slackbuild" && continue
    rel="${slackbuild#$SOURCE_DIR/}"

    # Force serial build for packages in SERIAL_BUILD_PKGS (parallel-make
    # races, bootstrap ordering requirements, etc.).
    pkgname_nj=$(basename "$slackbuild" .SlackBuild)
    forced_serial=0
    for sp in "${SERIAL_BUILD_PKGS[@]}"; do
        [ "$sp" = "$pkgname_nj" ] && forced_serial=1 && break
    done

    match=$(grep -n -m1 -E '^([[:space:]]*export[[:space:]]+)?[[:space:]]*NUMJOBS=' "$slackbuild" || true)

    if [ -n "$match" ]; then
        lineno=${match%%:*}
        line=${match#*:}

        # Preserve an "export " prefix if present on the original line.
        prefix=""
        [[ "$line" =~ ^[[:space:]]*export[[:space:]]+ ]] && prefix="export "

        # Style test on the value only, with trailing comment stripped.
        value=${line#*=}
        value=${value%%[[:space:]]#*}

        # Force -j1 for packages on the serial list, then preserve
        # explicit single-job requests from the original script,
        # then apply the default parallel flag.
        if [ $forced_serial -eq 1 ]; then
            new_line="${prefix}NUMJOBS=\${NUMJOBS:-\" -j1 \"}"
            style="-j1 (forced serial)"
        elif printf '%s\n' "$value" | grep -qE -- '(^|[^[:alnum:]_])-j[[:space:]]*1([^[:alnum:]]|$)' ; then
            new_line="${prefix}NUMJOBS=\${NUMJOBS:-\" -j1 \"}"
            style="-j1"
        elif printf '%s\n' "$value" | grep -qE -- '(^|[^[:alnum:]_])-j([^[:alpha:]]|$)' ; then
            new_line="${prefix}NUMJOBS=\${NUMJOBS:-\"$DEFAULT_JOBS_FLAG\"}"
            style="-j"
        else
            new_line="${prefix}NUMJOBS=\${NUMJOBS:-\"$DEFAULT_JOBS_COUNT\"}"
            style="bare"
        fi

        info "Patching NUMJOBS in $rel (style: $style, line $lineno)"

        sed -i "${lineno}s|.*|$new_line|" "$slackbuild"
        sed -i "2i $NUMJOBS_MARKER" "$slackbuild"

    elif grep -qE '\$\{?NUMJOBS' "$slackbuild"; then
        if [ $forced_serial -eq 1 ]; then
            inj_flag="-j1"
        else
            inj_flag="$DEFAULT_JOBS_FLAG"
        fi
        info "Injecting NUMJOBS default into $rel (used but never defined, flag: $inj_flag)"
        sed -i "2i $NUMJOBS_MARKER\nNUMJOBS=\${NUMJOBS:-\"$inj_flag\"}\nexport NUMJOBS" "$slackbuild"
    fi
done < <(find "$SOURCE_DIR" -name "*.SlackBuild" -type f | sort)

info "NUMJOBS patching finished."

#------------------------------------
# 2. Harden SlackBuilds — memory-corruption mitigations (maximum)
#------------------------------------
# Appends hardening flags to every SlackBuild that defines compiler
# or linker flags. Preserves the pristine original as <file>.orig the
# first time a SlackBuild is touched, so reverting is:
#
#     find "$SOURCE_DIR" -name '*.SlackBuild.orig' -print0 \
#       | while IFS= read -r -d '' f; do mv "$f" "${f%.orig}"; done
#
# Flags applied (maximum set):
#   Compiler-side variables (SLKCFLAGS, CFLAGS, CXXFLAGS, OPTIMIZ,
#   X86FLAGS32, X86FLAGS64):                       += -fhardened
#       -fhardened enables, in one flag:
#         -fstack-protector-strong    (canary)
#         -fstack-clash-protection    (stack clash)
#         -D_FORTIFY_SOURCE=3         (fortify)
#         -fPIE                       (position-independent code)
#         -fcf-protection=full        (Intel CET)
#         -ftrivial-auto-var-init=zero
#         -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack
#
#   Linker-side variables (LDFLAGS, SLKLDFLAGS):
#       += -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack
#       Repeated on the linker side so builds that link with ld
#       directly, bypassing the compiler driver, still get full RELRO
#       and PIE.
#
# Injection for files with no flag variables at all:
#   - If the file references $SLKCFLAGS without defining it: inject
#     exports of SLKCFLAGS and LDFLAGS at the top.
#   - Else, if the file invokes `make` directly (custom Makefile with
#     hardcoded CFLAGS): inject exports of CFLAGS/CXXFLAGS/LDFLAGS at
#     the top AND convert `make` to `make -e`, so the environment
#     overrides the Makefile's own assignments.
#
# Known failure modes with this set (handle per-package):
#   - static builds:            -pie conflicts with -static
#   - old autoconf link tests:  -fPIE breaks feature detection
#   - non-PIC x86 assembly:     relocation errors at link time
#   - zero-init-sensitive code: -ftrivial-auto-var-init=zero changes semantics
# When a package fails, edit its SlackBuild to drop the offending flag
# and remove the # CUSTOM_BUILD_HARDENED marker line so the patch pass
# leaves it alone on subsequent runs.

HARDEN_MARKER="# CUSTOM_BUILD_HARDENED"
HARDEN_CFLAGS="-fhardened"
HARDEN_LDFLAGS="-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,ibt -Wl,-z,shstk"



# Variables treated as compiler-flag assignments.
HARDEN_VARS_CFLAGS="SLKCFLAGS CFLAGS CXXFLAGS OPTIMIZ X86FLAGS32 X86FLAGS64"
# Variables treated as linker-flag assignments.
HARDEN_VARS_LDFLAGS="LDFLAGS SLKLDFLAGS"
# Detection regex: any line carrying a literal flag assignment.
HARDEN_DETECT_RE='^[^#]*\b(SLKCFLAGS|CFLAGS|CXXFLAGS|OPTIMIZ|X86FLAGS32|X86FLAGS64|LDFLAGS|SLKLDFLAGS)="'

info "Hardening SlackBuilds (maximum: canary + stack-clash + FORTIFY + PIE + CET + RELRO + zero-init)..."

# Append a flag to a variable assignment, but only if the flag is not
# already present on THIS variable's assignment. A file-wide grep would
# be wrong: patching CFLAGS would then make every later variable
# (CXXFLAGS, OPTIMIZ, ...) look already-done.
#
# Handles:
#   VAR="-O2 -fPIC"               -> VAR="-O2 -fPIC <flag>"
#   VAR='-O2 -fPIC'               -> VAR='-O2 -fPIC <flag>'
#   VAR=${VAR:-"-O2 -fPIC"}       -> VAR=${VAR:-"-O2 -fPIC <flag>"}
#   CFLAGS="-g $OPTIMIZ"          -> CFLAGS="-g $OPTIMIZ <flag>"
#   x86_64)  VAR="-O2"            -> x86_64)  VAR="-O2 <flag>"
# Does NOT touch comment lines.
add_flag() {
    local file="$1" var="$2" flag="$3"

    if grep -qE -- "^[^#]*\b${var}=[^#]*${flag}" "$file"; then
        return 0
    fi

    sed -i -E "/^[[:space:]]*#/! {
        s|(\b$var=\"[^\"]*)\"|\1 $flag\"|
        s|(\b$var='[^']*)'|\1 $flag'|
        s|(\b$var=\"?\$\{$var:-?\"[^\"]*)\"|\1 $flag\"|
    }" "$file"
}

harden_patched=0
harden_injected=0
harden_skipped=0
harden_unchanged=0
harden_nomatch=()

while IFS= read -r slackbuild; do

    [ -f "$slackbuild.orig" ] || cp "$slackbuild" "$slackbuild.orig"
    # Idempotency: skip anything already carrying the marker.
    if grep -q "$HARDEN_MARKER" "$slackbuild"; then
        harden_skipped=$((harden_skipped + 1))
        continue
    fi

    # Never touch the kernel series — it uses its own config and
    # gcc-in-kernel hardening options (CONFIG_STACKPROTECTOR etc.).
    [[ "$slackbuild" == */$KSERIES/* ]] && continue
    [[ "$slackbuild" == */d/gcc/* ]] && continue
    [[ "$slackbuild" == */z/busybox/* ]] && continue

    rel="${slackbuild#$SOURCE_DIR/}"

    # Detection: does this file have any literal flag-assignment line?
    if ! grep -qE "$HARDEN_DETECT_RE" "$slackbuild"; then
        if grep -q '\$SLKCFLAGS' "$slackbuild"; then
            # (a) File references $SLKCFLAGS without defining it.
            [ -f "$slackbuild.orig" ] || cp "$slackbuild" "$slackbuild.orig"
            sed -i "2i $HARDEN_MARKER\nexport SLKCFLAGS=\"\${SLKCFLAGS:--O2 -fPIC} $HARDEN_CFLAGS\"\nexport LDFLAGS=\"\${LDFLAGS:-} $HARDEN_LDFLAGS\"" "$slackbuild"
            info "  injected (SLKCFLAGS): $rel"
            harden_injected=$((harden_injected + 1))
        elif grep -qE '^[[:space:]]*make([[:space:]]|$)' "$slackbuild"; then
            # (b) File invokes make with no flag plumbing. Inject exports
            # and convert `make` to `make -e` so env overrides the
            # Makefile's own CFLAGS=/LDFLAGS= assignments. The -fPIC
            # addition matters for packages that build shared libs and
            # whose Makefile supplies no PIC flags of its own.
            [ -f "$slackbuild.orig" ] || cp "$slackbuild" "$slackbuild.orig"
            sed -i "2i $HARDEN_MARKER\nexport CFLAGS=\"\${CFLAGS:--O2} $HARDEN_CFLAGS -fPIC\"\nexport CXXFLAGS=\"\${CXXFLAGS:--O2} $HARDEN_CFLAGS -fPIC\"\nexport LDFLAGS=\"\${LDFLAGS:-} $HARDEN_LDFLAGS\"" "$slackbuild"
            sed -i -E 's|^([[:space:]]*)make[[:space:]]|\1make -e |' "$slackbuild"
            sed -i -E 's|^([[:space:]]*)make$|\1make -e|' "$slackbuild"
            info "  injected (make -e): $rel"
            harden_injected=$((harden_injected + 1))
        elif grep -qE '^[[:space:]]*(cc|gcc|g\+\+|\$CC|\$\{CC\})[[:space:]]' "$slackbuild"; then
            # (c) File invokes a compiler directly with no flag
            # variable at all. Common in single-file utility
            # SlackBuilds (rpm2tgz and similar). Inject exports of
            # CFLAGS/CXXFLAGS/LDFLAGS at the top, then rewrite the
            # compiler invocation to include them. The pattern is
            # anchored to start-of-line and requires whitespace
            # after the compiler name, so it does not match `bcc`
            # (start anchor), `clang` or `ccache` (word boundary),
            # or a `cc` inside a string literal or comment.
            [ -f "$slackbuild.orig" ] || cp "$slackbuild" "$slackbuild.orig"
            sed -i "2i $HARDEN_MARKER\nexport CFLAGS=\"\${CFLAGS:--O2} $HARDEN_CFLAGS -fPIC\"\nexport CXXFLAGS=\"\${CXXFLAGS:--O2} $HARDEN_CFLAGS -fPIC\"\nexport LDFLAGS=\"\${LDFLAGS:-} $HARDEN_LDFLAGS\"" "$slackbuild"
            sed -i -E 's|^([[:space:]]*)(cc\|gcc\|g\+\+)([[:space:]])|\1\2 $CFLAGS $LDFLAGS\3|' "$slackbuild"
            info "  injected (direct cc): $rel"
            harden_injected=$((harden_injected + 1))
                elif grep -qE '(^|[^a-zA-Z0-9_])(python[0-9.]*[[:space:]]+-m[[:space:]]+(build|pip|wheel)|pip[0-9]*[[:space:]]+(install|wheel)|python[0-9.]*[[:space:]]+setup\.py)' "$slackbuild"; then
            # (c) PEP 517 / setuptools frontend. `python3 -m build`,
            # `python3 -m pip`, `pip wheel`, and the older
            # `python3 setup.py` all read CFLAGS/CXXFLAGS/LDFLAGS from
            # the environment and merge them with the interpreter's
            # sysconfig defaults via setuptools' customize_compiler.
            # Inject exports so extension modules link with full RELRO,
            # CET, and FORTIFY. Without this the module links with the
            # interpreter's own defaults, which carry PIE and NX but not
            # the hardening set.
            [ -f "$slackbuild.orig" ] || cp "$slackbuild" "$slackbuild.orig"
            sed -i "2i $HARDEN_MARKER\nexport CFLAGS=\"\${CFLAGS:--O2} $HARDEN_CFLAGS -fPIC\"\nexport CXXFLAGS=\"\${CXXFLAGS:--O2} $HARDEN_CFLAGS -fPIC\"\nexport LDFLAGS=\"\${LDFLAGS:-} $HARDEN_LDFLAGS\"" "$slackbuild"
            info "  injected (PEP 517): $rel"
            harden_injected=$((harden_injected + 1))
        else
            harden_nomatch+=("$rel")
        fi
        continue
    fi

    # Snapshot for later diff. Only save once.
    [ -f "$slackbuild.orig" ] || cp "$slackbuild" "$slackbuild.orig"

    for var in $HARDEN_VARS_CFLAGS; do
        add_flag "$slackbuild" "$var" "$HARDEN_CFLAGS"
    done

    # LDFLAGS: two separate concerns, previously conflated into one
    # check.
    #
    # 1. Append the hardening flags to every LDFLAGS= assignment in
    #    the file, indented or not. Nested assignments inside a
    #    subshell (e.g. SWIG or Python binding blocks) need the flags
    #    too, scoped to their block.
    #
    # 2. Ensure the file has a top-level export the main autotools or
    #    make invocation will see. A nested LDFLAGS= is not evidence
    #    of a top-level export; SlackBuilds like libwebp that set
    #    LDFLAGS only inside a sub-build block would otherwise have
    #    their main link run without hardening. Check specifically
    #    for an unindented or export-prefixed assignment near the top
    #    of the file.
    for var in $HARDEN_VARS_LDFLAGS; do
        if grep -qE -- "^[^#]*\b${var}=" "$slackbuild"; then
            for flag in $HARDEN_LDFLAGS; do
                add_flag "$slackbuild" "$var" "$flag"
            done
        fi
    done

    ldflag_exported=0
    if head -10 "$slackbuild" | grep -qE '^(export[[:space:]]+)?LDFLAGS='; then
        ldflag_exported=1
    fi
    if [ $ldflag_exported -eq 0 ]; then
        sed -i "2i export LDFLAGS=\"\${LDFLAGS:-} $HARDEN_LDFLAGS\"" "$slackbuild"
    fi

    if cmp -s "$slackbuild.orig" "$slackbuild"; then
        warn "No change possible in $rel (variable-only assignments)"
        rm -f "$slackbuild.orig"
        harden_unchanged=$((harden_unchanged + 1))
        continue
    fi

    sed -i "2i $HARDEN_MARKER" "$slackbuild"
    info "  hardened: $rel"
    harden_patched=$((harden_patched + 1))

done < <(find "$SOURCE_DIR" \
              \( -name '*.SlackBuild' -o -name 'arch.use.flags' \) \
              -type f | sort)

info "Hardening summary: $harden_patched patched, $harden_injected injected, $harden_skipped already marked, $harden_unchanged no-op, ${#harden_nomatch[@]} without flag assignments"

if [ ${#harden_nomatch[@]} -gt 0 ]; then
    info "  No flag assignment found (expected for repack-only, meta, and firmware builds):"
    for p in "${harden_nomatch[@]}"; do
        echo "      $p"
    done
fi


#------------------------------------
# 2b. Fix inline literal flag assignments
#------------------------------------
# Some SlackBuilds use `CFLAGS=-O2 \` before ./configure — an inline
# assignment that replaces the exported CFLAGS for that one command,
# silently dropping the hardening flags the top-of-file export added.
# LDFLAGS is usually not clobbered, so the compile side loses -fPIE
# while the link side keeps -pie, and configure's PIE sanity test
# fails with "cannot run C compiled programs".
#
# Rewrites literal assignments to the ${VAR:-literal} form so the
# exported value wins when set, the literal becomes a fallback, and
# the resulting flag set is consistent across compile and link.
#
# Idempotent by construction: rewritten values contain '$', so they
# won't match again on subsequent runs. Values that are already
# references (contain '$') or already carry hardening markers
# (-fhardened, -pie, -Wl,-z,relro) are left alone.

if ! command -v gawk >/dev/null 2>&1; then
    warn "gawk not found; skipping inline-flag fix"
else
    info "Fixing inline literal flag assignments..."

    INLINE_AWK="$LOGDIR/inline-fix.awk"
    cat > "$INLINE_AWK" <<'AWK_EOF'
BEGIN {
    n = split("CFLAGS CXXFLAGS SLKCFLAGS LDFLAGS SLKLDFLAGS OPTIMIZ X86FLAGS32 X86FLAGS64", v, " ")
    vre = ""
    for (i = 1; i <= n; i++) vre = vre (vre ? "|" : "") v[i]
}
{
    line = $0

    # Skip comments
    if (line ~ /^[[:space:]]*#/) { print line; next }

    # Skip already-hardened lines (added by the hardening pass or this one)
    if (line ~ /-fhardened/ || line ~ /-pie/ || line ~ /-Wl,-z,relro/) {
        print line; next
    }

    # VAR="literal" rest
    if (match(line, "^([[:space:]]*(export[[:space:]]+)?)(" vre ")=\"([^\"$]*)\"(.*)$", m)) {
        printf "%s%s=\"${%s:-%s}\"%s\n", m[1], m[3], m[3], m[4], m[5]
        next
    }

    # VAR='literal' rest
    if (match(line, "^([[:space:]]*(export[[:space:]]+)?)(" vre ")='([^'$]*)'(.*)$", m)) {
        printf "%s%s=\"${%s:-%s}\"%s\n", m[1], m[3], m[3], m[4], m[5]
        next
    }

    # VAR=literal rest  (unquoted, no $)
    if (match(line, "^([[:space:]]*(export[[:space:]]+)?)(" vre ")=([^[:space:]$\"']+)(.*)$", m)) {
        printf "%s%s=\"${%s:-%s}\"%s\n", m[1], m[3], m[3], m[4], m[5]
        next
    }

    print line
}
AWK_EOF

    INLINE_FIXED=0
    INLINE_FILES=()

    while IFS= read -r slackbuild; do
        [[ "$slackbuild" == */$KSERIES/* ]] && continue
        [[ "$slackbuild" == */a/lilo/* ]] && continue

        # Only files that assign one of the known flag vars
        grep -qE '^[[:space:]]*(export[[:space:]]+)?(CFLAGS|CXXFLAGS|SLKCFLAGS|LDFLAGS|SLKLDFLAGS|OPTIMIZ|X86FLAGS32|X86FLAGS64)=' \
            "$slackbuild" || continue

        tmp="$slackbuild.inline-tmp"
        if gawk -f "$INLINE_AWK" "$slackbuild" > "$tmp"; then
            if ! cmp -s "$slackbuild" "$tmp"; then
                mv "$tmp" "$slackbuild"
                INLINE_FIXED=$((INLINE_FIXED + 1))
                INLINE_FILES+=("${slackbuild#$SOURCE_DIR/}")
            else
                rm -f "$tmp"
            fi
        else
            rm -f "$tmp"
            warn "gawk failed on $slackbuild (inline-flag fix skipped)"
        fi
    done < <(find "$SOURCE_DIR" \
                  \( -name '*.SlackBuild' -o -name 'arch.use.flags' \) \
                  -type f | sort)

    if [ ${#INLINE_FILES[@]} -gt 0 ]; then
        info "  inline-fixed: $INLINE_FIXED file(s)"
        for f in "${INLINE_FILES[@]}"; do
            echo "      $f"
        done
    else
        info "  no inline flag assignments needed fixing"
    fi
fi


#------------------------------------
# 3. Build list – dynamic series discovery, filtering, and sorting
#------------------------------------
BUILDLIST="$LOGDIR/buildlist"
mkdir -p "$LOGDIR"
rm -f "$LOGDIR/${scriptname}.log.failed"

info "Generating build list from all series in the source tree..."

> "$BUILDLIST"
for script in "$SOURCE_DIR"/*/*/*.SlackBuild; do
    pkgdir=$(dirname "$script")
    pkgname=$(basename "$pkgdir")
    sname=$(basename "$script" .SlackBuild)
    [ "$sname" = "$pkgname" ] || continue
    [ "$(uname -m)" = "x86_64" ] && [ "$pkgname" = "isapnptools" ] && continue
    # [ "$pkgname" = "devs" ] && continue
 #   [[ "$script" == */kernels/* ]] && continue
    echo "${script#$SOURCE_DIR/}" >> "$BUILDLIST"
done

# Also include two‑level SlackBuilds (e.g., $KSERIES/kernel-source.SlackBuild)
for script in "$SOURCE_DIR"/*/*.SlackBuild; do
    # Skip if already in the list (shouldn't happen, but safe)
    rel="${script#$SOURCE_DIR/}"
    if ! grep -qxF "$rel" "$BUILDLIST"; then
        # Ensure the series is not excluded (check against EXCLUDED_SERIES)
        series="${rel%%/*}"
        if [[ ! " ${EXCLUDED_SERIES[*]} " =~ " $series " ]]; then
            echo "$rel" >> "$BUILDLIST"
        fi
    fi
done

# ---- Determine the actual series present and the build order --------------
mapfile -t ALL_SERIES < <(find "$SOURCE_DIR" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort)

EXCLUDED_SERIES=("installer" "k612" 'k618')
for s in "${EXCLUDED_SERIES[@]}"; do
    ALL_SERIES=( "${ALL_SERIES[@]/$s}" )
done
mapfile -t ALL_SERIES < <(printf '%s\n' "${ALL_SERIES[@]}" | grep -v '^$')

PREFERRED_ORDER=(a l n tcl ap d x xap xfce y kde z)
SERIES_ORDER=()
for s in "${PREFERRED_ORDER[@]}"; do
    if [[ " ${ALL_SERIES[*]} " =~ " $s " ]]; then
        SERIES_ORDER+=("$s")
    fi
done
for s in "${ALL_SERIES[@]}"; do
    if [[ ! " ${SERIES_ORDER[*]} " =~ " $s " ]]; then
        SERIES_ORDER+=("$s")
    fi
done

SERIES_PATTERN="^($(IFS='|'; echo "${SERIES_ORDER[*]}"))/"
{
    for series in "${SERIES_ORDER[@]}"; do
        grep "^$series/" "$BUILDLIST" | sort -t/ -k2
    done
    grep -v -E "$SERIES_PATTERN" "$BUILDLIST" | sort -t/ -k1,1 -k2,2
} > "$BUILDLIST.sorted"
mv "$BUILDLIST.sorted" "$BUILDLIST"


info "Build list contains $(wc -l < "$BUILDLIST") packages across series: ${SERIES_ORDER[*]}"

# ---- Process blacklist file (package names + series: entries) -------------
declare -A SKIP_PKG_MAP
SKIP_SERIES_FILE=""

if [ -n "$BLACKLIST_FILE" ]; then
    [ -f "$BLACKLIST_FILE" ] || die "Blacklist file not found: $BLACKLIST_FILE"
    while IFS= read -r line; do
        line="${line%%#*}"
        line=$(echo "$line" | xargs)
        [ -z "$line" ] && continue

        if [[ "$line" =~ ^series:(.+)$ ]]; then
            s="${BASH_REMATCH[1]}"
            s=$(echo "$s" | xargs)
            [ -z "$s" ] && continue
            SKIP_SERIES_FILE="$SKIP_SERIES_FILE $s"
        else
            SKIP_PKG_MAP["$line"]=1
        fi
    done < "$BLACKLIST_FILE"
fi

if [ -n "$SKIP_SERIES_FILE" ]; then
    SKIP_SERIES="$SKIP_SERIES $SKIP_SERIES_FILE"
    SKIP_SERIES=$(echo "$SKIP_SERIES" | xargs)
fi

if [ -n "$SKIP_PACKAGES" ]; then
    for pkg in $SKIP_PACKAGES; do
        SKIP_PKG_MAP["$pkg"]=1
    done
fi

# ---- Auto-detect packages.list if not supplied ---------------------------
if [ -z "$ALLOWLIST_FILE" ]; then
    for candidate in \
        "$REPO_DIR/packages.list" \
        "/repo/packages.list" \
        "$(dirname "$REPO_DIR")/packages.list"; do
        if [ -f "$candidate" ]; then
            ALLOWLIST_FILE="$candidate"
            break
        fi
    done
fi

# ---- Build package allowlist-------
# One name per line; # starts a comment; blank lines ignored.
# If loaded, the X11 granular build will skip any official package
# whose base name is not in this set.
declare -A ALLOW_PKG
if [ -n "$ALLOWLIST_FILE" ] && [ -f "$ALLOWLIST_FILE" ]; then
    while IFS= read -r line; do
        line="${line%%#*}"
        line=$(echo "$line" | xargs)
        [ -z "$line" ] && continue
        ALLOW_PKG["$line"]=1
    done < "$ALLOWLIST_FILE"
    info "Allowlist loaded: ${#ALLOW_PKG[@]} package names from $ALLOWLIST_FILE"
else
    warn "No packages.list found; X11 granular build will not filter by allowlist."
fi

# Apply series filters (using combined SKIP_SERIES)
if [ -n "$BUILD_SERIES" ] || [ -n "$SKIP_SERIES" ]; then
    info "Filtering build list by series..."
    FILTERED="$LOGDIR/buildlist.filtered"
    > "$FILTERED"
    while IFS= read -r rel; do
        series=$(echo "$rel" | cut -d/ -f1)
        if [ -n "$SKIP_SERIES" ]; then
            for skip in $SKIP_SERIES; do
                [ "$series" = "$skip" ] && continue 2
            done
        fi
        if [ -n "$BUILD_SERIES" ]; then
            for allowed in $BUILD_SERIES; do
                [ "$series" = "$allowed" ] && echo "$rel" >> "$FILTERED" && continue 2
            done
        else
            echo "$rel" >> "$FILTERED"
        fi
    done < "$BUILDLIST"
    mv "$FILTERED" "$BUILDLIST"
    info "After series filtering: $(wc -l < "$BUILDLIST") packages."
fi

# Apply package blacklist
if [ ${#SKIP_PKG_MAP[@]} -gt 0 ]; then
    info "Blacklisting packages: ${!SKIP_PKG_MAP[*]}"
    FILTERED="$LOGDIR/buildlist.filtered"
    > "$FILTERED"
    while IFS= read -r rel; do
        pkgname=$(echo "$rel" | cut -d/ -f2)
        [ -z "${SKIP_PKG_MAP[$pkgname]}" ] && echo "$rel" >> "$FILTERED"
    done < "$BUILDLIST"
    mv "$FILTERED" "$BUILDLIST"
fi

info "Final build list: $(wc -l < "$BUILDLIST") packages."


# ---- Verify hardening on every SlackBuild in the final build list ----
info "Verifying hardening on all SlackBuilds in the build list..."

unhardened=()
no_slkcflags=()

while IFS= read -r rel; do
    script="$SOURCE_DIR/$rel"
    [ -f "$script" ] || continue

    if ! grep -qE "$HARDEN_DETECT_RE" "$script"; then
        no_slkcflags+=("$rel")
    elif ! grep -qF -- "$HARDEN_CFLAGS" "$script"; then
        unhardened+=("$rel")
    fi
done < "$BUILDLIST"

if [ ${#unhardened[@]} -gt 0 ]; then
    warn "UNHARDENED — these define flag assignments but lack $HARDEN_CFLAGS:"
    for p in "${unhardened[@]}"; do
        echo "      $p"
    done
    warn "Fix these before proceeding, or accept they build without canary/PIE."
fi

if [ ${#no_slkcflags[@]} -gt 0 ]; then
    info "NO FLAG ASSIGNMENTS — cannot be patched this way (kernel, firmware, repack-only):"
    for p in "${no_slkcflags[@]}"; do
        echo "      $p"
    done
fi

if [ ${#unhardened[@]} -eq 0 ] && [ ${#no_slkcflags[@]} -eq 0 ]; then
    info "Every SlackBuild in the build list is confirmed hardened."
fi


# ---- Copy and update custom kernel config ----
#
# Reads a seed config, merges it against the kernel tree's Kconfig via
# olddefconfig, and writes the result to both the in-chroot canonical
# location and the series' kernel-configs/ directory.
#

SEED_CONFIG="${SEED_CONFIG:-/repo/build/config.kernel}"

KERNEL_SRC=$(readlink -f /usr/src/linux)
if [ ! -f "$KERNEL_SRC/Makefile" ]; then
    warn "No kernel Makefile at $KERNEL_SRC/Makefile – skipping config update."
else
    INSTALLED_VERSION=$(awk '/^VERSION =/ {v=$3} /^PATCHLEVEL =/ {p=$3} /^SUBLEVEL =/ {s=$3} END {print v"."p"."s}' "$KERNEL_SRC/Makefile")
    if [ -z "$INSTALLED_VERSION" ] || [ "$INSTALLED_VERSION" = ".." ]; then
        warn "Failed to extract installed kernel version from $KERNEL_SRC/Makefile."
        INSTALLED_VERSION=""
    fi

    # Get the version expected by the source tree (from tarball filename)
    KERNEL_TARBALL=$(find "$SOURCE_DIR/$KSERIES" -maxdepth 1 -name 'linux-*.tar.xz' -print -quit)
    if [ -z "$KERNEL_TARBALL" ]; then
        warn "No kernel tarball found in $SOURCE_DIR/$KSERIES – skipping config update."
        SOURCE_TREE_VERSION=""
    else
        SOURCE_TREE_VERSION=$(basename "$KERNEL_TARBALL" .tar.xz | sed 's/^linux-//')
    fi

    # Only proceed if installed and source versions are identical.
    if [ -z "$INSTALLED_VERSION" ] || [ -z "$SOURCE_TREE_VERSION" ]; then
        warn "Cannot determine both kernel versions – skipping config update."
    elif [ "$INSTALLED_VERSION" != "$SOURCE_TREE_VERSION" ]; then
        warn "Installed kernel version ($INSTALLED_VERSION) does not match source tree version ($SOURCE_TREE_VERSION) – skipping config update."
    else
        info "Installed kernel version matches source tree version ($INSTALLED_VERSION). Updating config..."

        CONFIG_TARGET="$SOURCE_DIR/$KSERIES/kernel-configs/config-${INSTALLED_VERSION}.x64"
        CONFIG_TARGET_DIR=$(dirname "$CONFIG_TARGET")
        if [ ! -d "$CONFIG_TARGET_DIR" ]; then
            warn "Config target dir missing: $CONFIG_TARGET_DIR – creating."
            mkdir -p "$CONFIG_TARGET_DIR"
        fi

        if [ ! -f "$SEED_CONFIG" ]; then
            warn "Seed config not found at $SEED_CONFIG – olddefconfig will start from whatever .config is in $KERNEL_SRC."
        fi

        cd "$KERNEL_SRC" || die "Cannot cd to $KERNEL_SRC"

        if [ -f "$SEED_CONFIG" ]; then
            cp -f "$SEED_CONFIG" .config
            info "Seeded .config from $SEED_CONFIG"
        fi

        make olddefconfig

        cp -f .config "$SEED_CONFIG"
        cp -f .config "$CONFIG_TARGET"
        info "Updated kernel config saved to $CONFIG_TARGET and $SEED_CONFIG"
        cd /
    fi
fi

# ---- Ensure correct order for $KSERIES kernel packages ----
KSERIES_ORDER=("kernel-source" "kernel-generic" "kernel-headers")
TEMP_LIST="$LOGDIR/buildlist.temp"
> "$TEMP_LIST"

# First, write all non‑KSERIES entries
while IFS= read -r rel; do
    [[ "$rel" == $KSERIES/* ]] && continue
    echo "$rel" >> "$TEMP_LIST"
done < "$BUILDLIST"

# Then, write $KSERIES entries in the desired order
for pkg in "${KSERIES_ORDER[@]}"; do
    # Try the two‑level pattern first (direct in $KSERIES/)
    if grep -q "^$KSERIES/${pkg}.SlackBuild$" "$BUILDLIST"; then
        echo "$KSERIES/${pkg}.SlackBuild" >> "$TEMP_LIST"
    # Fallback to three‑level pattern (if someone restructured later)
    elif grep -q "^$KSERIES/$pkg/$pkg.SlackBuild$" "$BUILDLIST"; then
        echo "$KSERIES/$pkg/$pkg.SlackBuild" >> "$TEMP_LIST"
    fi
done

# Add any other $KSERIES packages (unlikely) at the end
while IFS= read -r rel; do
    [[ "$rel" == $KSERIES/* ]] && echo "$rel" >> "$TEMP_LIST"
done < <(grep "^$KSERIES/" "$BUILDLIST" | grep -v -E "$KSERIES/(kernel-source|kernel-generic|kernel-headers)(\.SlackBuild|/.*\.SlackBuild)")

mv "$TEMP_LIST" "$BUILDLIST"
info "Reordered $KSERIES packages: kernel-source → kernel-generic → kernel-headers"

#------------------------------------
# 3c. Move priority packages to the top of the build list
#------------------------------------
# Entries in PRIORITY_BUILD (typically the toolchain) are reordered
# to the front so they build first. The main loop's incremental check
# still applies — a second run skips them like any other package.
# No separate build path, no duplicated logic.

if [ ${#PRIORITY_BUILD[@]} -gt 0 ]; then
    # Build a fresh list with priority entries first, in array order.
    # Iterating forward and appending preserves the order; the previous
    # version prepended each entry, which reversed the array and put
    # the last element first.
    : > "$BUILDLIST.prio"

    for rel in "${PRIORITY_BUILD[@]}"; do
        if grep -qxF "$rel" "$BUILDLIST"; then
            echo "$rel" >> "$BUILDLIST.prio"
        else
            warn "priority entry not in build list: $rel"
        fi
    done

    grep -vxF -f "$BUILDLIST.prio" "$BUILDLIST" >> "$BUILDLIST.prio"

    mv "$BUILDLIST.prio" "$BUILDLIST"
    info "Priority entries moved to front: ${PRIORITY_BUILD[*]}"
fi

# Sanity check: for any SlackBuild in the priority list that sources
# a patches/ directory, make sure the directory exists and is not
# empty. The SlackBuild itself will fail if individual patches don't
# apply; this just catches the "empty patches dir" case before we
# spend an hour compiling.
for rel in "${PRIORITY_BUILD[@]}"; do
    sbfile="$SOURCE_DIR/$rel"
    srcdir=$(dirname "$sbfile")
    [ -f "$sbfile" ] || continue
    if grep -qE 'for patch in .*patches/' "$sbfile" && [ -d "$srcdir/patches" ]; then
        pcount=$(find "$srcdir/patches" -maxdepth 1 -type f \
            \( -name '*.patch' -o -name '*.diff' \
               -o -name '*.patch.gz' -o -name '*.diff.gz' \) | wc -l)
        info "  $(basename "$rel" .SlackBuild): $pcount patch file(s)"
        [ "$pcount" -gt 0 ] || die "$rel: patches/ exists but is empty"
    fi
done


# Clean previous build leftovers from $OUTPUT_LOCATION -----------------
rm -f "$OUTPUT_LOCATION"/*.t?z
> "$RETRY_LOG"



#------------------------------------
# 4. Incremental build functions
#------------------------------------
dir_hash() {
    find "$1" -type f -not -name '*.orig' -print0 \
        | sort -z | xargs -0 md5sum | md5sum | awk '{print $1}'
}

# expected_packages() {
#     local builddir="$1"
#     local scriptname=$(basename "$builddir").SlackBuild
#     ( cd "$builddir" && TMP="$TMP" OUTPUT="$OUTPUT_LOCATION" \
#       PRINT_PACKAGE_NAME=true bash "$scriptname" 2>/dev/null )
# }

expected_packages() {
    local builddir="$1"
    local scriptname
    scriptname=$(basename "$builddir").SlackBuild

    # Only run the SlackBuild if it actually implements the probe.
    # Any other package would otherwise execute a full build (tar,
    # configure, make, makepkg) purely as an up-to-date check — wasting
    # minutes and letting fd-juggling in autoreconf/configure leak
    # output past the "2>/dev/null" onto the caller's tty.
    #
    # The regex requires the variable to be *used* ("$PRINT_PACKAGE_NAME"
    # or "${PRINT_PACKAGE_NAME}"), not merely mentioned in a comment.
    if ! grep -qE '\$\{?PRINT_PACKAGE_NAME' "$builddir/$scriptname"; then
        return 0
    fi

    ( cd "$builddir" && TMP="$TMP" OUTPUT="$OUTPUT_LOCATION" \
      PRINT_PACKAGE_NAME=true bash "$scriptname" 2>/dev/null )
}

pkg_basename() {
    echo "$1" | sed -E 's/-[^-]+-[^-]+-[^-]+\.t[a-z]z$//'
}

pkg_version_string() {
    local file="$1"
    local name=$(basename "$file" .t?z)
    echo "${name#*-}"
}

# Multi-series output routing.
#
# Some SlackBuilds produce packages that belong to a different series
# than the SlackBuild's own directory. The canonical case is
# n/openssl/openssl.SlackBuild: it emits both openssl-*.txz (which
# belongs in n/) and openssl-solibs-*.txz (which belongs in a/, because
# the runtime libraries are needed by early base packages).
#
# $1 = default series (the SlackBuild's directory, e.g. "n")
# $2 = package filename          (e.g. "openssl-solibs-3.5.8-x86_64-2.txz")
route_series() {
    local default_series="$1"
    local pkg="$2"
    case "$pkg" in
        openssl-solibs-*) echo "a" ;;
        *)                echo "$default_series" ;;
    esac
}

cleanup_old_versions() {
    local series="$1" pkgfile="$2"
    local base=$(pkg_basename "$(basename "$pkgfile")")
    local current_version=$(pkg_version_string "$pkgfile")

    for candidate in "$CUSTOM_OUTPUT/$series/$base"-*.t?z; do
        [ -f "$candidate" ] || continue
        [ "$candidate" = "$CUSTOM_OUTPUT/$series/$(basename "$pkgfile")" ] && continue
        local cand_version=$(pkg_version_string "$candidate")
        if [ "$(printf '%s\n' "$current_version" "$cand_version" | sort -V | tail -1)" = "$current_version" ] && \
           [ "$current_version" != "$cand_version" ]; then
            rm -f "$candidate"
            rm -f "$candidate" "${candidate%.t?z}.txt" "${candidate}.asc"
            info "Removed old version: $(basename "$candidate")"
        fi
    done
}

build_and_install() {
    local rel="$1"
    local series=$(echo "$rel" | cut -d/ -f1)
    local scriptname=$(basename "$rel" .SlackBuild)   # <-- moved here

    # ---- Map $KSERIES packages to their official series ----
    local target_series="$series"
    if [[ "$rel" == $KSERIES/* ]]; then
        case "$scriptname" in
            kernel-source)  target_series="k" ;;
            kernel-generic) target_series="a" ;;
            kernel-headers) target_series="d" ;;
            *)              target_series="$KSERIES" ;;
        esac
    fi

    local fullpath="$SOURCE_DIR/$rel"
    local builddir=$(dirname "$fullpath")
    local scriptfile=$(basename "$fullpath")

    # ======================================================================
    #  X11 GRANULAR BUILD (only for x/x11/x11.SlackBuild)
    # ======================================================================
    if [[ "$rel" == x/x11/x11.SlackBuild ]]; then
        info "Entering X11 granular build check..."

        local x11_base="$SOURCE_DIR/x/x11"
        local x11_src="$x11_base/src"
        local official_dir="$PKG_DIR/x"
        local custom_dir="$CUSTOM_OUTPUT/$target_series"

        if [ ! -d "$official_dir" ]; then
            warn "Official X11 package directory not found: $official_dir"
            return 1
        fi

        # ---- Map every source tarball to (subdir, base) ----
        declare -A tarball_info   # key = "subdir:base" -> tarball path
        while IFS= read -r -d '' tarball; do
            local relpath=${tarball#$x11_src/}
            local subdir=$(echo "$relpath" | cut -d/ -f1)
            local filename=$(basename "$tarball")
            local base=$(echo "$filename" | rev | cut -f 2- -d - | rev)
            tarball_info["$subdir:$base"]="$tarball"
        done < <(find "$x11_src" -type f \
                    \( -name "*.tar.xz" -o -name "*.tar.lz" -o -name "*.tar.bz2" -o -name "*.tar.gz" \) \
                    -print0)

        # ---- base -> key reverse index (for exact lookup) ----
        declare -A base_to_key
        for key in "${!tarball_info[@]}"; do
            base_to_key["${key##*:}"]="$key"
        done

        # Resolve official package name to a source tarball key.
        # Exact match wins; otherwise longest-prefix match (handles
        # multi-output tarballs, e.g. xorg-server also produces
        # xorg-server-xephyr / -xnest / -xvfb).
        resolve_key() {
            local want="$1"
            if [ -n "${base_to_key[$want]}" ]; then
                printf '%s' "${base_to_key[$want]}"
                return
            fi
            local best="" bestlen=0 base
            for base in "${!base_to_key[@]}"; do
                case "$want" in
                    "$base"-*) ;;
                    *) continue ;;
                esac
                if [ ${#base} -gt $bestlen ]; then
                    best="${base_to_key[$base]}"
                    bestlen=${#base}
                fi
            done
            printf '%s' "$best"
        }

        declare -A to_build   # key = "subdir:base"
        local skipped_standalone=0 skipped_no_tarball=0 skipped_blacklist=0
        local skipped_not_needed=0

        for pkgfile in "$official_dir"/*.t?z; do
            [ -f "$pkgfile" ] || continue
            local filename=$(basename "$pkgfile")
            local pkgbase=$(pkg_basename "$filename")

            # Already present in custom output (exact filename) -> skip
            [ -f "$custom_dir/$filename" ] && continue

            # Blacklisted -> skip
            if [ -n "${SKIP_PKG_MAP[$pkgbase]}" ]; then
                skipped_blacklist=$((skipped_blacklist+1))
                continue
            fi

            # Not in packages.list -> skip
            if [ ${#ALLOW_PKG[@]} -gt 0 ] && [ -z "${ALLOW_PKG[$pkgbase]}" ]; then
                skipped_not_needed=$((skipped_not_needed+1))
                continue
            fi

            # Handled by a standalone SlackBuild -> skip
            if [ -f "$SOURCE_DIR/x/$pkgbase/$pkgbase.SlackBuild" ]; then
                skipped_standalone=$((skipped_standalone+1))
                continue
            fi

            local key
            key=$(resolve_key "$pkgbase")
            if [ -z "$key" ]; then
                warn "No source tarball for X11 package: $pkgbase (official $filename)"
                skipped_no_tarball=$((skipped_no_tarball+1))
                continue
            fi

            # Dedup: one tarball can back multiple official packages.
            [ -n "${to_build[$key]}" ] && continue
            to_build["$key"]=1
            info "Will build X11 $key (missing $filename in custom output)."
        done

        if [ ${#to_build[@]} -eq 0 ]; then
            info "All X11 packages already present in custom output."
            echo "X11 granular check: all packages already built." > "$LOGDIR/${scriptname}.log"
            return 0
        fi

        info "X11 build queue: ${#to_build[@]} source tarballs (skipped: $skipped_standalone standalone, $skipped_no_tarball no-tarball, $skipped_blacklist blacklisted, $skipped_not_needed not-in-list)"

        > "$LOGDIR/${scriptname}.log"
        rm -f "$LOGDIR/${scriptname}.log.failed"

        local x11_build_dir="$TMP/x11-build"
        rm -rf "$x11_build_dir"
        mkdir -p "$x11_build_dir" "$custom_dir"
        local overall_failed=0

        # ---- Build in x11.SlackBuild's subdir order ----
        local -a X11_SUBDIR_ORDER=(proto data util xcb lib app doc xserver driver font)

        for subdir in "${X11_SUBDIR_ORDER[@]}"; do
            local tarball_list
            tarball_list=$(find "$x11_src/$subdir" -maxdepth 1 -type f \
                \( -name "*.tar.xz" -o -name "*.tar.lz" -o -name "*.tar.bz2" -o -name "*.tar.gz" \) \
                -printf '%f\n' 2>/dev/null | sort)
            [ -z "$tarball_list" ] && continue

            while IFS= read -r filename; do
                [ -z "$filename" ] && continue
                local base=$(echo "$filename" | rev | cut -f 2- -d - | rev)
                local key="$subdir:$base"

                [ -n "${to_build[$key]}" ] || continue

                local before_files=$(mktemp)
                find "$x11_build_dir" -maxdepth 1 -name '*.t?z' -printf '%f\n' 2>/dev/null | sort > "$before_files"

                echo -n "Building X11 $subdir/$base ... "
                (
                    cd "$x11_base"
                    TMP="$TMP" \
                    SLACK_X_BUILD_DIR="$x11_build_dir" \
                    SKIPBUILT=no \
                    UPGRADE_PACKAGES=no \
                    bash "$scriptfile" "$subdir" "$base" &> "$LOGDIR/${base}.log"
                )
                if [ $? -ne 0 ]; then
                    warn "X11 build FAILED for $subdir/$base – see $LOGDIR/${base}.log"
                    overall_failed=1
                    echo "$(date '+%H:%M:%S') FAIL $rel → $subdir/$base (build error)" >> "$RETRY_LOG"
                    rm -f "$before_files"
                    continue
                fi

                local after_files=$(mktemp)
                find "$x11_build_dir" -maxdepth 1 -name '*.t?z' -printf '%f\n' 2>/dev/null | sort > "$after_files"
                local new_pkgs
                mapfile -t new_pkgs < <(comm -13 "$before_files" "$after_files")
                rm -f "$before_files" "$after_files"

                if [ ${#new_pkgs[@]} -eq 0 ]; then
                    warn "No package produced for $subdir/$base"
                    overall_failed=1
                    echo "$(date '+%H:%M:%S') FAIL $rel → $subdir/$base (no package)" >> "$RETRY_LOG"
                    continue
                fi

                local pkg_failed=0
                for pkgfile in "${new_pkgs[@]}"; do
                    if ! upgradepkg --install-new --reinstall "$x11_build_dir/$pkgfile" &>> "$LOGDIR/${base}.log"; then
                        warn "ERROR: upgradepkg failed for $pkgfile"
                        pkg_failed=1
                    elif ! cp "$x11_build_dir/$pkgfile" "$custom_dir/"; then
                        warn "ERROR: failed to copy $pkgfile to $custom_dir/"
                        pkg_failed=1
                    elif [ ! -s "$custom_dir/$pkgfile" ]; then
                        warn "ERROR: copy produced empty file: $custom_dir/$pkgfile"
                        pkg_failed=1
                    else
                        cleanup_old_versions "$target_series" "$pkgfile"
                        write_txt_for "$custom_dir/$pkgfile" "$target_series" "$custom_dir"
                    fi
                done

                if [ $pkg_failed -eq 1 ]; then
                    overall_failed=1
                    echo "$(date '+%H:%M:%S') FAIL $rel → $subdir/$base (install/copy error)" >> "$RETRY_LOG"
                    continue
                fi

                echo "OK"
            done <<< "$tarball_list"
        done

        if [ $overall_failed -eq 1 ]; then
            echo "$(date '+%H:%M:%S') FAIL $rel (some packages failed)" >> "$RETRY_LOG"
            touch "$LOGDIR/${scriptname}.log.failed"
            rm -rf "$x11_build_dir"
            return 1
        fi

        rm -rf "$x11_build_dir"
        return 0
    fi
    # ======================================================================


    # For $KSERIES packages, use hash-based check; for others, use PRINT_PACKAGE_NAME.
    if [[ "$rel" == $KSERIES/* ]]; then
        # Derive the kernel version from the source tarball so a version
        # bump invalidates the existing-package check. The old glob
        # `${scriptname}-*.t?z` matched any version and silently skipped
        # rebuilds after a kernel upgrade.
        local kernel_tarball kernel_ver existing_pkg
        kernel_tarball=$(find "$SOURCE_DIR/$KSERIES" -maxdepth 1 \
            -name 'linux-*.tar.xz' -print -quit)

        if [ -n "$kernel_tarball" ]; then
            kernel_ver=$(basename "$kernel_tarball" .tar.xz | sed 's/^linux-//')
            existing_pkg=$(compgen -G \
                "$CUSTOM_OUTPUT/$target_series/${scriptname}-${kernel_ver}-*.t?z" \
                | head -n1)
        else
            warn "No kernel tarball in $SOURCE_DIR/$KSERIES; cannot version-check $rel"
            existing_pkg=""
        fi

        if [ -n "$existing_pkg" ]; then
            info "Skipping $rel (amos64 build already up‑to‑date: $(basename "$existing_pkg"))."
            return 0
        fi
    else
        # ---- Non‑KSERIES packages: original logic ----
        mapfile -t expected_array < <(expected_packages "$builddir")
        if [ ${#expected_array[@]} -gt 0 ]; then
            local all_present=1
            for pkg in "${expected_array[@]}"; do
                local pkg_series
                pkg_series=$(route_series "$target_series" "$pkg")
                if [ ! -f "$CUSTOM_OUTPUT/$pkg_series/$pkg" ]; then
                    all_present=0
                    break
                fi
            done
            if [ $all_present -eq 1 ]; then
                info "Skipping $rel (amos64 build already up‑to‑date)."
                return 0
            fi
            for pkg in "${expected_array[@]}"; do
                rm -f "$OUTPUT_LOCATION/$pkg"
            done
        else
            warn "$rel does not support PRINT_PACKAGE_NAME – will always rebuild."
        fi
    fi

    local was_failed=0
    [ -f "$LOGDIR/${scriptname}.log.failed" ] && was_failed=1

    local before_files=$(mktemp)
    find "$OUTPUT_LOCATION" -maxdepth 1 -name '*.t?z' -printf '%f\n' 2>/dev/null | sort > "$before_files"

    echo -n "Building $rel ... "
    ( cd "$builddir" && TMP="$TMP" OUTPUT="$OUTPUT_LOCATION" \
      bash "$scriptfile" &> "$LOGDIR/${scriptname}.log" )
    if [ $? -ne 0 ]; then
        warn "FAILED – see $LOGDIR/${scriptname}.log"
        mv "$LOGDIR/${scriptname}.log" "$LOGDIR/${scriptname}.log.failed"
        echo "$(date '+%H:%M:%S') FAIL $rel" >> "$RETRY_LOG"
        rm -f "$before_files"
        return 1
    fi

    local after_files=$(mktemp)
    find "$OUTPUT_LOCATION" -maxdepth 1 -name '*.t?z' -printf '%f\n' 2>/dev/null | sort > "$after_files"
    local new_packages=( $(comm -13 "$before_files" "$after_files") )
    rm -f "$before_files" "$after_files"

    if [ ${#new_packages[@]} -eq 0 ]; then
        warn "FAILED – no new package found in $OUTPUT_LOCATION"
        mv "$LOGDIR/${scriptname}.log" "$LOGDIR/${scriptname}.log.failed"
        echo "$(date '+%H:%M:%S') FAIL $rel (no package)" >> "$RETRY_LOG"
        return 1
    fi

    local install_failed=0
    for pkg in "${new_packages[@]}"; do
        if ! upgradepkg --install-new --reinstall "$OUTPUT_LOCATION/$pkg" &>> "$LOGDIR/${scriptname}.log"; then
            warn "ERROR: upgradepkg failed for $pkg"
            install_failed=1
        fi
    done
    if [ $install_failed -eq 1 ]; then
        mv "$LOGDIR/${scriptname}.log" "$LOGDIR/${scriptname}.log.failed"
        echo "$(date '+%H:%M:%S') FAIL $rel (install error)" >> "$RETRY_LOG"
        return 1
    fi

    for pkg in "${new_packages[@]}"; do
        local pkg_series
        pkg_series=$(route_series "$target_series" "$pkg")
        mkdir -p "$CUSTOM_OUTPUT/$pkg_series"
        if ! cp "$OUTPUT_LOCATION/$pkg" "$CUSTOM_OUTPUT/$pkg_series/"; then
            warn "ERROR: failed to copy $pkg to $CUSTOM_OUTPUT/$pkg_series/"
            mv "$LOGDIR/${scriptname}.log" "$LOGDIR/${scriptname}.log.failed"
            echo "$(date '+%H:%M:%S') FAIL $rel (copy error)" >> "$RETRY_LOG"
            return 1
        fi
        [ ! -s "$CUSTOM_OUTPUT/$pkg_series/$pkg" ] && {
            warn "ERROR: copy produced empty file: $CUSTOM_OUTPUT/$pkg_series/$pkg"
            return 1
        }
        cleanup_old_versions "$pkg_series" "$pkg"
        write_txt_for "$CUSTOM_OUTPUT/$pkg_series/$pkg" "$pkg_series" "$CUSTOM_OUTPUT/$pkg_series"
    done

    for dir in "$TMP/package-$scriptname" "$TMP/$scriptname-"*; do
        [ -d "$dir" ] && rm -rf "$dir"
    done
    
    if [ $was_failed -eq 1 ]; then
        echo "$(date '+%H:%M:%S') ✅ RETRY SUCCESS $rel" >> "$RETRY_LOG"
        echo ">>> 🔄 RETRY SUCCESS: $rel"
    else
        echo "$(date '+%H:%M:%S') SUCCESS $rel" >> "$RETRY_LOG"
    fi
    echo "OK"
    rm -f "$LOGDIR/${scriptname}.log.failed"
    return 0
}


PKG_DIR="$REPO_DIR/slackware64"
Z_OUT="$CUSTOM_OUTPUT/z"
Z_DEPS_CONF="$SOURCE_DIR/z/z-deps.conf"

if [ "$NOZ" = "1" ]; then
    warn "Skipping z rebuild-trigger check (--noz)."
    warn "  Stale z packages will NOT be detected. Verify manually if needed."
elif [ -d "$Z_OUT" ] && compgen -G "$Z_OUT/*.t?z" >/dev/null; then
    info "Checking z rebuild triggers..."

    if [ ! -d "$PKG_DIR" ] || ! compgen -G "$PKG_DIR/*/*.t?z" >/dev/null; then
        warn "  PKG_DIR empty or missing ($PKG_DIR); cannot check z staleness."
    else
        declare -A BASE_SONAMES=() PROVIDED=() ZPROVIDED=() NEEDED_SET=() \
                   Z_NEEDS=() STALE=()

        for s in libc.so.6 libm.so.6 libpthread.so.6 libdl.so.2 librt.so.1 \
                 libresolv.so.2 libnsl.so.1 libutil.so.1 libanl.so.1 \
                 libBrokenLocale.so.1 libmvec.so.1 libcrypt.so.1 \
                 ld-linux-x86-64.so.2 \
                 libgcc_s.so.1 libstdc++.so.6 libgomp.so.1 libatomic.so.1 \
                 libitm.so.1 libquadmath.so.0 libgfortran.so.5 \
                 libasound.so.2 libatopology.so.2; do
            BASE_SONAMES[$s]=1
        done

        # Append reason to STALE[zs], preserving any earlier reason.
        add_stale() {
            local zs="$1" reason="$2"
            if [ -n "${STALE[$zs]:-}" ]; then
                STALE[$zs]="${STALE[$zs]}; $reason"
            else
                STALE[$zs]="$reason"
            fi
        }

        # Prefer tmpfs
        if [ -d /dev/shm ] && [ -w /dev/shm ]; then
            WORK=$(mktemp -d /dev/shm/zcheck.XXXXXX)
        else
            WORK=$(mktemp -d /tmp/zcheck.XXXXXX)
        fi

        # Track background PIDs so we can kill them on interrupt
        JOB_PIDS=()
        cleanup() {
            # Kill any remaining background jobs
            if [ ${#JOB_PIDS[@]} -gt 0 ]; then
                kill -9 "${JOB_PIDS[@]}" 2>/dev/null || true
                wait 2>/dev/null || true
            fi
            rm -rf "$WORK" 2>/dev/null || true
        }
        trap cleanup EXIT INT TERM

        # Extract once, emit sonames (provide or need)
        scan_package() {
            local txz="$1" mode="$2"
            local ext="$WORK/$(basename "$txz").$$"
            mkdir -p "$ext"
            tar xf "$txz" -C "$ext" 2>/dev/null || { rm -rf "$ext"; return; }

            local f dyn soname
            while IFS= read -r -d '' f; do
                readelf -hW "$f" 2>/dev/null \
                    | grep -qE 'Machine:.*(Advanced Micro Devices X86-64|Intel 80386)' \
                    || continue
                dyn=$(readelf -dW "$f" 2>/dev/null) || continue
                [ -n "$dyn" ] || continue
                if [ "$mode" = provide ]; then
                    soname=$(awk '/SONAME/{gsub(/[][]/,"",$5); print $5; exit}' <<< "$dyn")
                    if [ -n "$soname" ]; then
                        echo "$soname"
                    elif [[ "$f" == *.so || "$f" == *.so.* ]]; then
                        basename "$f"
                    fi
                else
                    awk '/NEEDED/{gsub(/[][]/,"",$5); print $5}' <<< "$dyn"
                fi
            done < <(find "$ext" -type f \( -executable -o -name '*.so' -o -name '*.so.*' \) -print0 2>/dev/null)

            rm -rf "$ext"
        }

        # ---- Collect PROVIDED from PKG_DIR (parallel) ----
        mapfile -t pkg_list < <(compgen -G "$PKG_DIR/*/*.t?z")
        maxjobs=$(nproc 2>/dev/null || echo 4)
        jobcount=0
        i=0
        JOB_PIDS=()
        for txz in "${pkg_list[@]}"; do
            [ -f "$txz" ] || continue
            scan_package "$txz" provide > "$WORK/pkg.$i" &
            JOB_PIDS+=($!)
            jobcount=$((jobcount + 1))
            i=$((i + 1))
            if [ "$jobcount" -ge "$maxjobs" ]; then
                wait -n 2>/dev/null || wait
                jobcount=$((jobcount - 1))
            fi
        done
        wait
        JOB_PIDS=()

        # Merge
        for f in "$WORK"/pkg.*; do
            [ -f "$f" ] || continue
            while IFS= read -r s; do
                [ -n "$s" ] && [ -z "${BASE_SONAMES[$s]:-}" ] && PROVIDED[$s]=1
            done < "$f"
        done

        # ---- Collect ZPROVIDED + Z_NEEDS from Z_OUT (parallel) ----
        mapfile -t z_list < <(compgen -G "$Z_OUT/*.t?z")
        jobcount=0
        i=0
        JOB_PIDS=()
        for ztxz in "${z_list[@]}"; do
            [ -f "$ztxz" ] || continue
            (
                scan_package "$ztxz" provide > "$WORK/zprov.$i"
                scan_package "$ztxz" need    > "$WORK/zneed.$i"
                zs=$(basename "$ztxz")
                zs="${zs%.txz}"; zs="${zs%.tgz}"; zs="${zs%.tbz}"; zs="${zs%.tlz}"
                zs="${zs%-x86_64-*}"; zs="${zs%-i686-*}"; zs="${zs%-noarch-*}"
                zs="${zs%%-[0-9]*}"
                echo "$zs" > "$WORK/zname.$i"
            ) &
            JOB_PIDS+=($!)
            jobcount=$((jobcount + 1))
            i=$((i + 1))
            if [ "$jobcount" -ge "$maxjobs" ]; then
                wait -n 2>/dev/null || wait
                jobcount=$((jobcount - 1))
            fi
        done
        wait
        JOB_PIDS=()

        # Merge ZPROVIDED and build Z_NEEDS
        for f in "$WORK"/zprov.*; do
            [ -f "$f" ] || continue
            while IFS= read -r s; do
                [ -n "$s" ] && [ -z "${BASE_SONAMES[$s]:-}" ] && ZPROVIDED[$s]=1
            done < "$f"
        done

        for nf in "$WORK"/zneed.*; do
            [ -f "$nf" ] || continue
            idx=${nf##*.}
            zs=$(cat "$WORK/zname.$idx" 2>/dev/null) || continue
            NEEDED_SET=()
            while IFS= read -r s; do
                [ -n "$s" ] || continue
                [ -n "${BASE_SONAMES[$s]:-}" ] && continue
                NEEDED_SET[$s]=1
            done < "$nf"

            if [ ${#NEEDED_SET[@]} -gt 0 ]; then
                Z_NEEDS[$zs]=$(printf '%s\n' "${!NEEDED_SET[@]}" | sort -u | paste -sd' ' -)
            else
                Z_NEEDS[$zs]=""
            fi
        done

        # ---- Check missing sonames ----
        for zs in "${!Z_NEEDS[@]}"; do
            missing=""
            for s in ${Z_NEEDS[$zs]}; do
                [ -n "${PROVIDED[$s]:-}" ]  && continue
                [ -n "${ZPROVIDED[$s]:-}" ] && continue
                missing="$missing $s"
            done
            [ -n "$missing" ] && add_stale "$zs" "missing soname:$(echo $missing | xargs | sed 's/^/ /')"
        done

        # ---- 2) Extra edges from z-deps.conf ----
        if [ -f "$Z_DEPS_CONF" ]; then
            while IFS= read -r line; do
                line="${line%%#*}"
                line=$(printf '%s' "$line" | xargs)
                [ -z "$line" ] && continue
                read -ra fields <<< "$line"
                zs="${fields[0]}"
                [ ${#fields[@]} -lt 2 ] && continue

                zs_txz=$(ls "$Z_OUT/${zs}"-[0-9]*.t?z 2>/dev/null | head -1)
                [ -n "$zs_txz" ] || continue

                for dep in "${fields[@]:1}"; do
                    dep_a=$(ls "$PKG_DIR"/*/"${dep}"-[0-9]*.t?z 2>/dev/null | head -1)
                    dep_z=$(ls "$Z_OUT/${dep}"-[0-9]*.t?z 2>/dev/null | head -1)

                    if [ -n "$dep_a" ]; then
                        if [ "$dep_a" -nt "$zs_txz" ]; then
                            add_stale "$zs" "extra-dep: $dep (a-y txz newer than $zs txz)"
                        fi
                    elif [ -n "$dep_z" ]; then
                        if [ "$dep_z" -nt "$zs_txz" ]; then
                            add_stale "$zs" "extra-dep: $dep (z txz newer than $zs txz)"
                        fi
                    else
                        add_stale "$zs" "extra-dep: $dep (not found)"
                    fi
                done
            done < "$Z_DEPS_CONF"
        fi

        # Normal cleanup (trap will also run)
        cleanup
        trap - EXIT INT TERM

        # ---- Report ----
        if [ ${#STALE[@]} -gt 0 ]; then
            echo "" >&2
            warn "──────────────────────────────────────────────────────────────"
            warn " STALE Z's: rebuild required before this run can proceed"
            warn "──────────────────────────────────────────────────────────────"
            warn ""
            warn "These z's are already built but their dependencies changed"
            warn "in ways the current build would not pick up:"
            warn ""
            for zs in $(printf '%s\n' "${!STALE[@]}" | sort); do
                warn "    $zs"
                warn "        ${STALE[$zs]}"
                for f in "$Z_OUT/${zs}"-[0-9]*.t?z; do
                    [ -f "$f" ] && warn "        rm $f"
                done
            done
            warn ""
            warn "Delete the listed .txz file(s) and re-run."
            warn "──────────────────────────────────────────────────────────────"
            die "stale z packages detected."
        fi

        info "  no stale z's."
    fi
fi

#------------------------------------
# 5. Main build loop – automatic retry until everything is done
#------------------------------------

info "Starting automated build..."
[ -n "$BUILD_SERIES" ] && info "Only building series: $BUILD_SERIES"
[ -n "$SKIP_SERIES" ] && info "Skipping series: $SKIP_SERIES"
[ ${#SKIP_PKG_MAP[@]} -gt 0 ] && info "Blacklisted packages: ${!SKIP_PKG_MAP[*]}"
echo ""

pass=0
# while true; do
while [ $pass -eq 0 ]; do
    pass=$((pass + 1))
    echo "============================================================="
    echo " PASS $pass"
    echo "============================================================="

    failures=0
    succeeded=0

    while IFS= read -r rel; do
        [ -z "$rel" ] && continue
        if build_and_install "$rel"; then
            succeeded=$((succeeded + 1))
        else
            failures=$((failures + 1))
         #   die "Failed to build $rel. See $LOGDIR/${rel//\//_}.log.failed"
        fi
    done < "$BUILDLIST"

    echo ""
    echo "-----------------------------------------------------------------"
    echo " PASS $pass SUMMARY:"
    echo "   ✅ Processed (built or skipped): $succeeded"
    echo "   ❌ Still failing:                $failures"
    echo "-----------------------------------------------------------------"

    if [ $failures -eq 0 ]; then
        echo ""
        echo "   ✅✅✅  BUILD DONE  ✅✅✅"
        echo "   All packages have been built successfully."
        break
    else
        echo "   ⏳ Retrying failed packages in the next pass..."
        echo ""
        echo "   Currently failing packages (will be retried):"
        for f in "$LOGDIR"/*.log.failed; do
            pkg=$(basename "$f" .log.failed)
            echo "      - $pkg"
        done
        echo ""
    fi
done

compgen -G "$CUSTOM_OUTPUT/l/aaa_glibc-solibs-*.txz" > /dev/null && \
    mv $CUSTOM_OUTPUT/l/aaa_glibc-solibs-*.txz $CUSTOM_OUTPUT/a/
compgen -G "$CUSTOM_OUTPUT/a/ncurses-*.txz" > /dev/null && \
    mv $CUSTOM_OUTPUT/a/ncurses-*.txz $CUSTOM_OUTPUT/l/


#------------------------------------
# Move testing packages to amos64-testing
#------------------------------------
# Packages listed in the TESTING_LIST array (testing-packages.sh, sourced)
# are moved out of $CUSTOM_OUTPUT/<series>/ into
# $REPO_DIR/amos64-testing/<series>/. The series directory is preserved
# so slackpkg / upgradepkg resolve paths relative to the series root.
#
# The list is a shell fragment declaring TESTING_LIST as an array:
#
#     #testing list
#     TESTING_LIST=(
#         # known deps for sway
#         wayland
#         libdrm
#         ...
#     )
#
# Sourced as code — the file lives next to this script under the repo and
# must be trusted. Point $TESTING_LIST_FILE elsewhere to override the
# default location.
#
# Sidecars travel with the package: <base>.txt (description, written by
# write_txt_for earlier) and <pkg>.asc (signature, if any).
#
# Packages already present under amos64-testing/ from a previous run are
# not re-moved — counted as "already present" and skipped, so the block
# is idempotent across reruns. Packages listed but absent from both
# trees are reported as missing; the script does not abort (a testing
# list is allowed to name packages that were blacklisted or not built
# on this architecture).

SCRIPT_DIR="${SCRIPT_DIR:-$(dirname "$(readlink -f "$0")")}"
TESTING_LIST_FILE="${TESTING_LIST_FILE:-$SCRIPT_DIR/testing-packages.sh}"

unset TESTING_LIST
if [ -f "$TESTING_LIST_FILE" ]; then
    # shellcheck disable=SC1090
    . "$TESTING_LIST_FILE" || die "failed to source $TESTING_LIST_FILE"
fi

# Sanity: after sourcing, TESTING_LIST must either be undeclared (empty
# list file, all comments — legitimate) or an array. A string assignment
# in the file is a typo and would silently break the loop below.
if declare -p TESTING_LIST >/dev/null 2>&1; then
    if ! declare -p TESTING_LIST | grep -q '^declare -a'; then
        die "$TESTING_LIST_FILE: TESTING_LIST must be declared as an array"
    fi
else
    TESTING_LIST=()
fi

if [ ${#TESTING_LIST[@]} -gt 0 ]; then
    info "Moving ${#TESTING_LIST[@]} testing package(s) to $REPO_DIR/amos64-testing/"
    mkdir -p "$REPO_DIR/amos64-testing"

    testing_moved=0
    testing_refreshed=0
    testing_unchanged=0
    testing_missing=()

    # Deduplicate the list.
    mapfile -t TESTING_LIST < <(printf '%s\n' "${TESTING_LIST[@]}" | sort -u)

    # Basenames present in the testing tree. Value is newline-terminated
    # so a base name that appears in more than one series is fully
    # accounted for (needed both for refresh-removal and for the
    # unchanged-counter to report the right thing).
    declare -A IN_TESTING=()   # base -> "path\npath\n..."
    for tdir in "$REPO_DIR/amos64-testing"/*/; do
        [ -d "$tdir" ] || continue
        for tfile in "$tdir"/*.t?z; do
            [ -f "$tfile" ] || continue
            tbase=$(pkg_basename "$(basename "$tfile")")
            IN_TESTING["$tbase"]+="$tfile"$'\n'
        done
    done

    # Basenames present in $CUSTOM_OUTPUT.
    declare -A IN_CUSTOM=()    # base -> "path\npath\n..."
    for series_dir in "$CUSTOM_OUTPUT"/*/; do
        [ -d "$series_dir" ] || continue
        series=$(basename "$series_dir")
        for pkgfile in "$series_dir"/*.t?z; do
            [ -f "$pkgfile" ] || continue
            pbase=$(pkg_basename "$(basename "$pkgfile")")
            IN_CUSTOM["$pbase"]+="$pkgfile"$'\n'
        done
    done

    for pkg in "${TESTING_LIST[@]}"; do
        has_testing=0
        has_custom=0
        [ -n "${IN_TESTING[$pkg]:-}" ] && has_testing=1
        [ -n "${IN_CUSTOM[$pkg]:-}"  ] && has_custom=1

        # Neither tree → missing.
        if [ $has_testing -eq 0 ] && [ $has_custom -eq 0 ]; then
            testing_missing+=("$pkg")
            continue
        fi

        # Testing-only → leave as-is, nothing new to move.
        if [ $has_testing -eq 1 ] && [ $has_custom -eq 0 ]; then
          #  info "  unchanged: $pkg (already in testing, no newer build)"
            testing_unchanged=$((testing_unchanged + 1))
            continue
        fi

        # Custom output has a build for this package. If testing also
        # holds a copy, remove every old entry (and sidecars) before
        # moving the new one in. Testing is a fresh snapshot of the
        # current custom build, not an archive of every version ever
        # seen.
        refreshed=0
        if [ $has_testing -eq 1 ]; then
            refreshed=1
            while IFS= read -r oldfile; do
                [ -z "$oldfile" ] && continue
                old_base="${oldfile%.t?z}"
                rm -f "$oldfile" "${old_base}.txt" "${oldfile}.asc"
               # info "  removed old testing: $(basename "$oldfile")"
            done <<< "${IN_TESTING[$pkg]}"
        fi

        # Move every matching custom-output file into its series dir
        # under testing, carrying the .txt and .asc sidecars along.
        while IFS= read -r pkgfile; do
            [ -z "$pkgfile" ] && continue
            series=$(basename "$(dirname "$pkgfile")")
            dest_series="$REPO_DIR/amos64-testing/$series"
            mkdir -p "$dest_series"

            if mv -f "$pkgfile" "$dest_series/"; then
               # info "  moved: $series/$(basename "$pkgfile")"
                testing_moved=$((testing_moved + 1))
            else
                warn "  move failed: $pkgfile"
                continue
            fi

            base_path="${pkgfile%.t?z}"
            [ -f "${base_path}.txt" ] && mv -f "${base_path}.txt" "$dest_series/"
            [ -f "${pkgfile}.asc"    ] && mv -f "${pkgfile}.asc"    "$dest_series/"
        done <<< "${IN_CUSTOM[$pkg]}"

        [ $refreshed -eq 1 ] && testing_refreshed=$((testing_refreshed + 1))
    done

    # if [ ${#testing_missing[@]} -gt 0 ]; then
    #     warn "Testing packages listed but not found in either tree:"
    #     for p in "${testing_missing[@]}"; do
    #         echo "    $p"
    #     done
    # fi

    # Warn about testing entries not named in TESTING_LIST. Do not
    # delete — a typo or a temporarily-removed entry would silently
    # drop a package. Admin prunes manually.
    declare -A LISTED=()
    for p in "${TESTING_LIST[@]}"; do LISTED["$p"]=1; done

    ORPHANS=()
    for tbase in "${!IN_TESTING[@]}"; do
        [ -n "${LISTED[$tbase]:-}" ] && continue
        ORPHANS+=("$tbase")
    done

    if [ ${#ORPHANS[@]} -gt 0 ]; then
        warn "Testing entries not in TESTING_LIST (left in place):"
        for o in $(printf '%s\n' "${ORPHANS[@]}" | sort); do
            echo "    $o"
        done
    fi

    info "Testing move: $testing_moved moved ($testing_refreshed refreshed), $testing_unchanged unchanged, ${#testing_missing[@]} missing."
else
    if [ -f "$TESTING_LIST_FILE" ]; then
        info "Testing list $TESTING_LIST_FILE is empty; nothing to move."
    else
        warn "No $TESTING_LIST_FILE; no testing packages will be moved."
    fi
fi

ANNODE_SRC="$SOURCE_DIR/z/annode"
ANNODE_DST="$CUSTOM_OUTPUT/z/annode"

if [ -d "$ANNODE_SRC" ]; then
    info "Copying source/z/annode to $ANNODE_DST ..."
    mkdir -p "$CUSTOM_OUTPUT/z"
    rm -rf "$ANNODE_DST"
    cp -a "$ANNODE_SRC" "$ANNODE_DST"
    annode_files=$(find "$ANNODE_DST" -type f 2>/dev/null | wc -l)
    info "  copied $annode_files file(s)"
else
    info "No source/z/annode/ present; nothing to copy"
    rm -rf "$ANNODE_DST"
fi

#------------------------------------
# 5b. Swap the bundled tor inside annode's anne-node.jar
#------------------------------------
# anne-node.jar ships a static tor plus GeoIP databases under
# tor/linux/. Those are replaced here with the versions from the tor
# package produced by this build, so the jar's tor matches the system
# tor at the target (same version, same dynamic-library expectations,
# same defaults). tor/mac/ and tor/win/ were pruned upstream by
# sync.sh and are not touched here.
#
# Source layout inside the tor .txz:
#   usr/bin/tor              -> jar  tor/linux/tor
#   usr/share/tor/geoip      -> jar  tor/linux/geoip
#   usr/share/tor/geoip6     -> jar  tor/linux/geoip6

ANNODE_ZIP="$ANNODE_DST/anne-node.zip"

#------------------------------------
# 5b. Swap the bundled tor inside annode's anne-node.jar
#------------------------------------
# anne-node.jar ships a static tor plus GeoIP databases under
# tor/linux/. Those are replaced here with the versions from the tor
# package produced by this build, so the jar's tor matches the system
# tor at the target (same version, same dynamic-library expectations,
# same defaults). tor/mac/ and tor/win/ were pruned upstream by
# sync.sh and are not touched here.
#
# Source layout inside the tor .txz:
#   usr/bin/tor              -> jar  tor/linux/tor
#   usr/share/tor/geoip      -> jar  tor/linux/geoip
#   usr/share/tor/geoip6     -> jar  tor/linux/geoip6

ANNODE_ZIP="$ANNODE_DST/anne-node.zip"

if [ -f "$ANNODE_ZIP" ]; then
    info "Replacing bundled tor in $(basename "$ANNODE_ZIP") ..."

    command -v unzip >/dev/null 2>&1 || die "unzip not found in PATH (required for annode swap)"
    command -v zip   >/dev/null 2>&1 || die "zip not found in PATH (required for annode swap)"

    # locate the tor package ----
    mapfile -t tor_candidates < <(compgen -G "$CUSTOM_OUTPUT/z/tor-[0-9]*.t?z" | sort -V)
    [ ${#tor_candidates[@]} -gt 0 ] || die "No tor-*.t?z found in $CUSTOM_OUTPUT/z/"
    TOR_PKG="${tor_candidates[-1]}"
    info "  tor package: $(basename "$TOR_PKG")"

    TMP_TOR=$(mktemp -d)
    TMP_ZIP=$(mktemp -d)
    annode_tor_cleanup() { rm -rf "$TMP_TOR" "$TMP_ZIP"; }
    trap annode_tor_cleanup EXIT INT TERM

    # extract the new binaries from their packages --------------
    tar -xf "$TOR_PKG" -C "$TMP_TOR" \
        usr/bin/tor usr/share/tor/geoip usr/share/tor/geoip6 \
        || die "Failed to extract tor/geoip/geoip6 from $(basename "$TOR_PKG")"

    # unpack the outer zip
    unzip -q -o "$ANNODE_ZIP" -d "$TMP_ZIP" \
        || die "Failed to unzip $ANNODE_ZIP"

    JAR="$TMP_ZIP/anne-node.jar"
    [ -f "$JAR" ] || die "anne-node.jar not found inside $ANNODE_ZIP"

    # stage the replacement files at their in-jar paths ---------
    TMP_STAGE="$TMP_TOR/stage"
    mkdir -p "$TMP_STAGE/tor/linux" \
             "$TMP_STAGE/linux-x86-64" \
             "$TMP_STAGE/com/sun/jna/linux-x86-64"

    cp "$TMP_TOR/usr/bin/tor"          "$TMP_STAGE/tor/linux/tor"
    cp "$TMP_TOR/usr/share/tor/geoip"  "$TMP_STAGE/tor/linux/geoip"
    cp "$TMP_TOR/usr/share/tor/geoip6" "$TMP_STAGE/tor/linux/geoip6"
    chmod 755 "$TMP_STAGE/tor/linux/tor"
    chmod 644 "$TMP_STAGE/tor/linux/geoip" "$TMP_STAGE/tor/linux/geoip6"

    # Ensure staged files have a fresh mtime so zip will replace
    # any existing entries even if deletion were to fail.
    touch "$TMP_STAGE/tor/linux/tor" \
          "$TMP_STAGE/tor/linux/geoip" \
          "$TMP_STAGE/tor/linux/geoip6"

    # update the jar------
    entries=(
        tor/linux/tor
        tor/linux/geoip
        tor/linux/geoip6
    )

    # Delete existing entries so the replacement is unconditional.
    # Only attempt deletion if the entry is actually present; fail
    # if deletion does not succeed.
    for entry in "${entries[@]}"; do
        if unzip -Z1 "$JAR" | grep -Fxq "$entry"; then
            zip -d "$JAR" "$entry" \
                || die "Failed to delete $entry from $JAR"
        fi
    done

    # Add the new entries.
    ( cd "$TMP_STAGE" && zip -q "$JAR" "${entries[@]}" ) \
        || die "zip update of $JAR failed"

    # verify the jar carries all five entries before repacking --
    # Each entry must appear exactly once, and its content must match
    # the staged file.
    for entry in "${entries[@]}"; do
        count=$(unzip -Z1 "$JAR" | grep -Fxc "$entry")
        if [ "$count" -ne 1 ]; then
            die "Expected exactly one $entry in $JAR, found $count"
        fi

        unzip -p "$JAR" "$entry" > "$TMP_TOR/verify_entry" \
            || die "Failed to extract $entry from $JAR for verification"

        if ! cmp -s "$TMP_TOR/verify_entry" "$TMP_STAGE/$entry"; then
            die "Content of $entry in $JAR does not match staged file"
        fi
    done
    rm -f "$TMP_TOR/verify_entry"

    # repack the outer zip
    NEW_ZIP="$ANNODE_ZIP.new"
    rm -f "$NEW_ZIP"
    ( cd "$TMP_ZIP" && zip -q -r "$NEW_ZIP" . ) \
        || die "Failed to rebuild $ANNODE_ZIP"
    mv -f "$NEW_ZIP" "$ANNODE_ZIP"

    # verify the outer zip
    ziplist=$(unzip -l "$ANNODE_ZIP" 2>/dev/null || true)
    if ! grep -q 'anne-node.jar' <<< "$ziplist"; then
        die "Rebuilt $ANNODE_ZIP is missing anne-node.jar"
    fi
    unset ziplist

    info "  replaced tor, geoip, geoip6 in $(basename "$ANNODE_ZIP")"

    annode_tor_cleanup
    trap - EXIT INT TERM
else
    info "No anne-node.zip at $ANNODE_ZIP; skipping annode swap"
fi

echo "All packages built. Custom output: $CUSTOM_OUTPUT/"

#------------------------------------
# 6. Obsolete check – custom packages not found in upstream Slackware repo (exact filename)
#------------------------------------
info "Obsolete check: custom packages missing from official binary repo (exact filename match)..."
MISSING=0
for series_dir in "$CUSTOM_OUTPUT"/*/; do
    series=$(basename "$series_dir")
    [ ! -d "$PKG_DIR/$series" ] && continue
    for pkgfile in "$series_dir"/*.t?z; do
        [ -f "$pkgfile" ] || continue
        filename=$(basename "$pkgfile")
        if [ ! -f "$PKG_DIR/$series/$filename" ]; then
            warn "Not in upstream: $series/$filename"
            MISSING=$((MISSING + 1))
        fi
    done
done

if [ $MISSING -eq 0 ]; then
    info "Obsolete check passed – every custom package filename exists in the official repo."
else
    warn "Obsolete check finished – $MISSING custom package(s) have no exact filename match in the official repo."
fi


#------------------------------------
# 7. Reverse obsolete check – official packages missing from amos64 build
#------------------------------------

info "Reverse check: official packages missing from amos64 build (exact filename match across all series)..."

# Check if kde5 is in SKIP_SERIES
skip_kde5=false
if [ -n "$SKIP_SERIES" ]; then
    for s in $SKIP_SERIES; do
        if [ "$s" = "kde5" ]; then
            skip_kde5=true
            break
        fi
    done
fi

declare -A official_files
declare -A official_series

# Collect all official package filenames (skip excluded series and skipped series)
for series_dir in "$PKG_DIR"/*/; do
    series=$(basename "$series_dir")
    # Skip series that are never built (installer, k612, etc.)
    [[ " ${EXCLUDED_SERIES[*]} " =~ " $series " ]] && continue
    # Skip series that are globally skipped via --skip-series or blacklist
    if [ -n "$SKIP_SERIES" ]; then
        for skip in $SKIP_SERIES; do
            [ "$series" = "$skip" ] && continue 2
        done
    fi
    for pkgfile in "$series_dir"/*.t?z; do
        [ -f "$pkgfile" ] || continue
        filename=$(basename "$pkgfile")
        official_files["$filename"]=1
        official_series["$filename"]="$series"
    done
done

# Collect all custom package filenames (any series)
declare -A custom_files
for custom_dir in "$CUSTOM_OUTPUT"/*/; do
    series=$(basename "$custom_dir")
    for pkgfile in "$custom_dir"/*.t?z; do
        [ -f "$pkgfile" ] || continue
        filename=$(basename "$pkgfile")
        custom_files["$filename"]=1
    done
done

MISSING_OFFICIAL=0
for filename in "${!official_files[@]}"; do
    # Skip if already present in custom output
    [ -n "${custom_files[$filename]}" ] && continue

    # Extract base package name (without version) to check blacklist
    base=$(pkg_basename "$filename")
    # Skip if package is blacklisted
    [ -n "${SKIP_PKG_MAP[$base]}" ] && continue

    series="${official_series[$filename]}"

    # ---- Special handling for kde5 module ----
    # If series is "kde" and kde5 is skipped, skip any package whose base name ends with '5'
    if [ "$series" = "kde" ] && $skip_kde5 && [[ "$base" == *5 ]]; then
        continue
    fi

    warn "Not in custom: $series/$filename"
    MISSING_OFFICIAL=$((MISSING_OFFICIAL + 1))
done

if [ $MISSING_OFFICIAL -eq 0 ]; then
    info "Reverse check passed – every non‑blacklisted official package filename exists in the amos64 build (across all series)."
else
    warn "Reverse check finished – $MISSING_OFFICIAL official package(s) have no exact filename match in the amos64 build (blacklisted packages/series/modules are ignored)."
fi

info "Checking doinst.sh consistency across the final tree vs source. If the output is empty, every package whose source recipe expects config() is carrying it correctly through the build. If it lists MISMATCH packages, those are the ones you need to rebuild after fixing their SlackBuild."
for p in "$CUSTOM_OUTPUT"/*/*.txz; do
    series=$(basename "$(dirname "$p")")
    base=$(basename "$p" .txz)
    pkg="${base%%-[0-9]*}"
    srcdir="$SOURCE_DIR/$series/$pkg"

    has_src=0
    if [ -f "$srcdir/doinst.sh" ]; then
        grep -q 'config()' "$srcdir/doinst.sh" && has_src=1
    elif [ -f "$srcdir/doinst.sh.gz" ]; then
        zcat "$srcdir/doinst.sh.gz" 2>/dev/null | grep -q 'config()' && has_src=1
    fi
    [ "$has_src" -eq 1 ] || continue

    tmp=$(mktemp)
    bsdtar -xOf "$p" install/doinst.sh 2>/dev/null > "$tmp"
    grep -q 'config()' "$tmp" || echo "MISMATCH: $p"
    rm -f "$tmp"
done
info "DONE."
info "Any malformed package names eg.. *--*.t?z?"
for bad in "$CUSTOM_OUTPUT"/*/*--*.t?z; do
    [ -f "$bad" ] || continue
    warn "Malformed package (empty version): ${bad#$CUSTOM_OUTPUT/}"
done
info "ALL DONE."