#!/bin/bash
# iso.sh
# Build the AM·OS ISO(s) from the repo tree.
#
# Run from anywhere. Paths are derived from the script's own location:
# iso.sh lives at <repo>/install/iso.sh, so REPO_DIR (repo root) is one
# level up, and INSTALL_DIR is the directory the script sits in.
#
# The repo tree IS the ISO structure, with a small set of exclusions:
#   - amos64/       packaged into amos64/ on the ISO
#   - boot/         transformed into isolinux/ (extracted from packages)
#   - slackware64/  package tree, not shipped, used only for comparison with upstream
#   - overrides/    build-time only
#   - source/       shipped only with --with-source
#   - source-am/ shipped only with --with-source
#   - install/      only the runtime scripts are shipped
#   - top-level build artefacts (ISO image, its checksums, root CHECKSUMS.md5)
#
# With --with-source, two ISOs are produced: the primary ISO (no source
# tree) and a second ISO that also carries source/ and source-am/.
#
# Run as root.

set -eu
PATH="$PATH:/usr/local/sbin:/usr/sbin:/sbin"
export PATH
BUILD_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" # repo/build
REPO_DIR="$(cd "$BUILD_DIR/.." && pwd)"       # repo
cd "$REPO_DIR"
trap 'cd "$REPO_DIR" 2>/dev/null || true; echo "*** FAILED on line $LINENO ***" >&2' ERR



ISO_PROFILE="${ISO_PROFILE:-ghostnet}"
PROFILE_FILE="$REPO_DIR/profiles/${ISO_PROFILE}.conf"
[ -f "$PROFILE_FILE" ] || { echo "unknown ISO profile: $ISO_PROFILE" >&2; exit 1; }
# shellcheck disable=SC1090
. "$PROFILE_FILE"
echo "ISO profile:     $PROFILE_NAME ($PROFILE_DESC)"


AMOS_BUILD="${AMOS_BUILD:-$REPO_DIR}"
AMOS_PRODUCTION="$AMOS_BUILD/amos64"

BOOT="${BOOT:-$REPO_DIR/boot}"

SYSLINUX_PKG_GLOB="${SYSLINUX_PKG_GLOB:-syslinux-*.txz}"
KERNEL_PKG_GLOB="${KERNEL_PKG_GLOB:-kernel-generic-*.txz}"

PKGMAIN="amos64"
RELEASE="current"
ARCH="x86_64"

STAGING="${STAGING:-/tmp/amos-build}"
ISODIR="$STAGING/iso"

OUTISO="${OUTISO:-$REPO_DIR/amos-${RELEASE}-${ISO_PROFILE}-${ARCH}.iso}"
OUTISO_SRC="${OUTISO_SRC:-$REPO_DIR/amos-${RELEASE}-${ISO_PROFILE}-src-${ARCH}.iso}"

# Runtime install scripts. The ISO's install/ folder carries exactly
# these; build-only tools (iso.sh, sign.sh) stay on the build host.
INSTALL_DIR="${INSTALL_DIR:-$REPO_DIR/install}"
INSTALL_SHIP=(common.sh setup.sh install.sh)

# Documentation and helper tools.
AUDIT_DIR="${AUDIT_DIR:-$REPO_DIR/audit}"

# Initrd and overlay sources. These live under install/ alongside the
# runtime scripts. The ISO's /install/ folder is populated from the
# INSTALL_SHIP whitelist above, so build tools (iso.sh, sign.sh,
# build-initrd.sh) and source inputs (initrd-src/, install-overlay/)
# do not leak into it.
#
INITRD_BUILD="${INITRD_BUILD:-$INSTALL_DIR/build-initrd.sh}"
INITRD_SRC="${INITRD_SRC:-$INSTALL_DIR/initrd-src}"
INITRD_IMG="${INITRD_IMG:-$INSTALL_DIR/initrd.img}"
# OVERLAY_SRC="${OVERLAY_SRC:-$INSTALL_DIR/install-overlay}"

# annode payload sources.
ANNODE_SRC="${ANNODE_SRC:-$REPO_DIR/amos64/z/annode}"    # zips
ANNODE_INSTALL="${ANNODE_INSTALL:-$INSTALL_DIR/annode}"     # scripts, amosfeed, peers

# sign.sh lives with the other build tools.
SIGN_SRC="${SIGN_SRC:-$BUILD_DIR/sign.sh}"

DEFAULT_PW="${DEFAULT_PW:-slack}"

GPG_KEY="${GPG_KEY:-radanne@anne.media}"
GPG_PUBKEY="${GPG_PUBKEY:-$AMOS_BUILD/AMOS-GPG-KEY}"

VIDEO_RES="${VIDEO_RES:-"1280x720-32"}"
ISO_DATE="${ISO_DATE:-$(date -u +%Y%m%d%H%M%S00)}"
ELILO_EFI_SRC="${ELILO_EFI_SRC:-}"

WITH_SOURCE=0

# ---- Args ----
while [ $# -gt 0 ]; do
  case "$1" in
    --with-source) WITH_SOURCE=1 ; shift ;;
    -h|--help)
      sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
      exit 0
      ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

# ---- Sanity ----
[ -f "$SIGN_SRC" ]                          || { echo "No sign.sh at $SIGN_SRC"; exit 1; }
[ -w "$REPO_DIR" ]                           || { echo "Cannot write to $REPO_DIR"; exit 1; }
[ -w "$(dirname "$STAGING")" ]              || { echo "Cannot write to $STAGING"; exit 1; }
[ -d "$BOOT" ]                              || { echo "No $BOOT"; exit 1; }
[ -f "$BOOT/isolinux.cfg" ]                 || { echo "No $BOOT/isolinux.cfg"; exit 1; }
[ -d "$AMOS_PRODUCTION" ]                   || { echo "No $AMOS_PRODUCTION -- run sync.sh first."; exit 1; }
[ -d "$INSTALL_DIR" ]                       || { echo "No install/ at $INSTALL_DIR"; exit 1; }
[ -f "$INSTALL_DIR/setup.sh" ]              || { echo "No install/setup.sh"; exit 1; }
[ -f "$INSTALL_DIR/install.sh" ]            || { echo "No install/install.sh"; exit 1; }
[ -f "$INSTALL_DIR/common.sh" ]             || { echo "No install/common.sh"; exit 1; }
[ -d "$AUDIT_DIR" ]                         || { echo "No audit/ at $AUDIT_DIR"; exit 1; }
[ -f "$AUDIT_DIR/AUDIT.TXT" ]               || { echo "No audit/AUDIT.TXT"; exit 1; }
[ -f "$AUDIT_DIR/README-HARDENING.txt" ]    || { echo "No audit/README-HARDENING.txt"; exit 1; }
[ -f "$GPG_PUBKEY" ]                        || { echo "No GPG public key at $GPG_PUBKEY"; exit 1; }
gpg --list-secret-keys "$GPG_KEY" >/dev/null 2>&1 \
                                            || { echo "No secret key for '$GPG_KEY' in keyring."; exit 1; }
command -v openssl >/dev/null               || { echo "openssl required on the build host."; exit 1; }
command -v make    >/dev/null               || { echo "make required on the build host."; exit 1; }
{ command -v cc >/dev/null || command -v gcc >/dev/null; } \
                                            || { echo "C compiler (cc/gcc) required on the build host."; exit 1; }
{ command -v mkfs.vfat >/dev/null || command -v mkfs.fat >/dev/null; } \
                                            || { echo "mkfs.vfat (dosfstools) required."; exit 1; }
command -v mcopy >/dev/null                 || { echo "mcopy (mtools) required."; exit 1; }

if [ "$WITH_SOURCE" = "1" ]; then
  if [ ! -d "$REPO_DIR/source" ] && [ ! -d "$REPO_DIR/source-am" ]; then
    echo "WARNING: --with-source given but no source/ or source-am/ at repo root." >&2
    echo "         Skipping source ISO." >&2
    WITH_SOURCE=0
  fi
fi

echo "Output ISO:      $OUTISO"
[ "$WITH_SOURCE" = "1" ] && echo "Output Src ISO:  $OUTISO_SRC"
echo "Production:      $AMOS_PRODUCTION"
echo "Boot assets:     $BOOT"
echo "initrd:          $INITRD_IMG"
echo "Install scripts: $INSTALL_DIR  (shipped: ${INSTALL_SHIP[*]})"
echo "Audit:           $AUDIT_DIR"
echo "annode src:      $ANNODE_SRC"
echo "video res:       $VIDEO_RES"
echo "signing key:     $GPG_KEY"
echo "public key:      $GPG_PUBKEY"

rm -rf "$STAGING"
mkdir -p "$ISODIR"

cat > "$ISODIR/type" <<EOF
$PROFILE_NAME
EOF

# =============================================================================
# Populate $ISODIR
# =============================================================================

# --- 1. Mirror the repo tree ---
mirror_repo() {
  local with_source="$1"
  local entry base f

  for entry in "$REPO_DIR"/*; do
    [ -e "$entry" ] || continue
    base=$(basename "$entry")

    case "$base" in
      amos-*.iso|amos-*.iso.*|CHECKSUMS.md5|CHECKSUMS.md5.asc)
        continue ;;
      slackware64|amos-testing)
        continue ;;
      amos64|boot)
        continue ;;
      source|source-am|build|overrides)
        [ "$with_source" = "1" ] || continue
        ;;
      install)
        mkdir -p "$ISODIR/install"
        for f in "${INSTALL_SHIP[@]}"; do
          [ -f "$INSTALL_DIR/$f" ] || continue
          cp -a "$INSTALL_DIR/$f" "$ISODIR/install/"
          case "$f" in
            common.sh) chmod 644 "$ISODIR/install/$f" ;;
            *)         chmod 755 "$ISODIR/install/$f" ;;
          esac
        done

        # AppArmor setup: script + profiles. Ships as a subdirectory
        # because it's a set of files, not a single script.
        if [ -d "$INSTALL_DIR/apparmor" ]; then
          cp -a "$INSTALL_DIR/apparmor" "$ISODIR/install/"
          chmod 755 "$ISODIR/install/apparmor/install-apparmor.sh"
          chmod 644 "$ISODIR/install/apparmor/profiles/"*
          echo "  install/apparmor/ ($(ls "$INSTALL_DIR/apparmor/profiles/" | wc -l) profile(s))"
        fi
        continue ;;
    esac

    cp -a "$entry" "$ISODIR/"
  done

  mkdir -p "$ISODIR/install"
}

# --- 2. Boot assets (isolinux.bin, vmlinuz, isolinux.cfg, etc.) ---
stage_boot_assets() {
  mkdir -p "$ISODIR/isolinux"

  local syslinux_pkg tmp isolinux_bin c32 c32_path
  syslinux_pkg=$(find "$AMOS_PRODUCTION" -name "$SYSLINUX_PKG_GLOB" 2>/dev/null | head -n1)
  [ -n "$syslinux_pkg" ] || { echo "ERROR: no $SYSLINUX_PKG_GLOB under $AMOS_PRODUCTION." >&2; exit 1; }
  echo "  syslinux package: $syslinux_pkg"

  tmp=$(mktemp -d)
  tar -xf "$syslinux_pkg" -C "$tmp"

  isolinux_bin=$(find "$tmp" -name 'isolinux.bin' -print -quit)
  [ -n "$isolinux_bin" ] || { echo "ERROR: isolinux.bin not in $syslinux_pkg." >&2; rm -rf "$tmp"; exit 1; }
  cp -a "$isolinux_bin" "$ISODIR/isolinux/isolinux.bin"
  chmod u+w "$ISODIR/isolinux/isolinux.bin"
  echo "  isolinux.bin <- $isolinux_bin"

  local isohdpfx_bin
  isohdpfx_bin=$(find "$tmp" -name 'isohdpfx.bin' -print -quit)
  if [ -n "$isohdpfx_bin" ]; then
    cp -a "$isohdpfx_bin" "$ISODIR/isolinux/isohdpfx.bin"
    echo "  isohdpfx.bin <- $isohdpfx_bin"
  else
    echo "WARNING: isohdpfx.bin not found in syslinux package. Hybrid boot might fail." >&2
  fi

  for c32 in ldlinux.c32 menu.c32 libcom32.c32 libutil.c32; do
    c32_path=$(find "$tmp" -name "$c32" -print -quit)
    if [ -n "$c32_path" ]; then
      cp -a "$c32_path" "$ISODIR/isolinux/$c32"
      echo "  $c32"
    fi
  done
  rm -rf "$tmp"

  local kernel_pkg vmlinuz
  kernel_pkg=$(find "$AMOS_PRODUCTION" -name "$KERNEL_PKG_GLOB" 2>/dev/null | head -n1)
  [ -n "$kernel_pkg" ] || { echo "ERROR: no $KERNEL_PKG_GLOB under $AMOS_PRODUCTION." >&2; exit 1; }
  echo "  kernel package: $kernel_pkg"

  tmp=$(mktemp -d)
  tar -xf "$kernel_pkg" -C "$tmp"
  vmlinuz=$(find "$tmp" -name 'vmlinuz*' -print -quit)
  [ -n "$vmlinuz" ] || { echo "ERROR: no vmlinuz in $kernel_pkg." >&2; rm -rf "$tmp"; exit 1; }
  cp -a "$vmlinuz" "$ISODIR/isolinux/vmlinuz"
  echo "  vmlinuz <- $vmlinuz"
  rm -rf "$tmp"

  cp -a "$BOOT/isolinux.cfg" "$ISODIR/isolinux/isolinux.cfg"
  echo "  isolinux.cfg"
  local f
  for f in message.txt f2.txt README.TXT; do
    if [ -f "$BOOT/$f" ]; then
      cp -a "$BOOT/$f" "$ISODIR/isolinux/$f"
      echo "  $f"
    fi
  done
}

# --- 3. Root hash fallback ---
stage_root_hash() {
  echo "=== Generating default root hash ==="
  local h
  h=$(openssl passwd -6 "$DEFAULT_PW")
  printf '%s\n' "$h" > "$ISODIR/.root.hash"
  chmod 600 "$ISODIR/.root.hash"
  echo "  /root.hash"
}

stage_debug_key() {
  local key="${AMOS_DEBUG_KEY:-$HOME/.ssh/amos-initrd}"
  local akey="$INSTALL_DIR/initrd-src/etc/dropbear/authorized_keys"

  mkdir -p "$(dirname "$akey")"

  if [ ! -f "$key" ]; then
    echo "=== Generating initrd debug SSH key ==="
    ssh-keygen -t ed25519 -N '' -C 'amos-initrd-debug' -f "$key" >/dev/null
    echo "  created: $key"
  else
    echo "=== Reusing existing initrd debug SSH key ==="
    echo "  $key"
  fi

  cp -a "$key.pub" "$akey"
  chmod 644 "$akey"
  echo "  pubkey -> initrd-src/etc/dropbear/authorized_keys"
}

# --- 4. initrd ---
ensure_initrd() {
  if [ ! -x "$INITRD_BUILD" ]; then
    echo
    echo "ERROR: no executable at $INITRD_BUILD" >&2
    echo "       install/build-initrd.sh must be present and executable." >&2
    exit 1
  fi

  echo
  echo "=== Building initrd ==="
  "$INITRD_BUILD" "$ISO_PROFILE" || { echo "ERROR: initrd build failed" >&2; exit 1; }
}

# --- 5.and initrd into isolinux.cfg ---
apply_initrd() {
 if [ -f "$INITRD_IMG" ]; then
    echo "=== Staging initrd ==="
    cp -a "$INITRD_IMG" "$ISODIR/isolinux/initrd.img"
    chmod u+w "$ISODIR/isolinux/initrd.img"
    echo "  isolinux/initrd.img"
  else
    echo "ERROR: $INITRD_IMG not found; ISO will not boot without it." >&2
    exit 1
  fi
}

# stage_install_overlay() {
#   if [ -d "$OVERLAY_SRC" ]; then
#     echo "=== Copying install-overlay ==="
#     rm -rf "$ISODIR/install/install-overlay"
#     mkdir -p "$ISODIR/install"
#     cp -a "$OVERLAY_SRC" "$ISODIR/install/install-overlay"
#     echo "  /install/install-overlay/ -> install.sh will overlay this"
#   fi
# }

# --- 7. Sign production packages ---
sign_packages() {
  echo
  echo "=== Signing packages in $AMOS_PRODUCTION ==="
  BUILD="$AMOS_PRODUCTION" GPG_KEY="$GPG_KEY" "$SIGN_SRC" \
    || { echo "ERROR: sign.sh failed" >&2; exit 1; }
}

# --- 8. Copy packages into ISO's amos64/ ---
stage_packages() {
  echo
  echo "  profile: $PROFILE_NAME; blacklisted families: ${ISO_BLACKLIST[*]}"
  echo "=== Copying packages from $AMOS_PRODUCTION ==="

    # Return 0 if the package name (no extension) is in ISO_BLACKLIST.
  # Return 0 if the package is allowed, 1 if it should be excluded.
  # Whitelist takes precedence over blacklist.
  is_package_allowed() {
    local pkg="$1" pat
    
    # 1. Check Whitelist (if defined and not empty)
    if [ ${#ISO_WHITELIST[@]} -gt 0 ]; then
      for pat in "${ISO_WHITELIST[@]}"; do
        case "$pkg" in
          "$pat"|"$pat"-[0-9]*) return 0 ;;
        esac
      done
      return 1 # Not found in whitelist
    fi

    # 2. Check Blacklist (if defined and not empty)
    if [ ${#ISO_BLACKLIST[@]} -gt 0 ]; then
      for pat in "${ISO_BLACKLIST[@]}"; do
        case "$pkg" in
          "$pat"|"$pat"-[0-9]*) return 1 ;; # Found in blacklist
        esac
      done
    fi

    return 0 # Allowed by default if no lists match
  }

  # Copy one package family: <pkg>.txz and its .asc, unless excluded.
  copy_one_pkg() {
    local src="$1" destdir="$2"
    local base pkgname
    base=$(basename "$src")
    pkgname="${base%.t[gx]z}"
    
    if ! is_package_allowed "$pkgname"; then
      echo "  iso-excluded: $base"
      return 0
    fi
    
    cp -a "$src" "$destdir/"
    [ -f "${src}.asc" ] && cp -a "${src}.asc" "$destdir/"
  }

  copy_series() {
    local srcdir="$1" destdir="$2"
    local f

    # Packages (filtered).
    while IFS= read -r -d '' f; do
      copy_one_pkg "$f" "$destdir"
    done < <(find "$srcdir" -maxdepth 1 -type f \
                \( -name '*.txz' -o -name '*.tgz' \) \
                ! -name 'kernel-source-*' \
                -print0)

    # Series-level text files (slack-desc, PACKAGES.TXT fragments),
    # excluding the excluded package's own slack-desc.
    find "$srcdir" -maxdepth 1 -type f -name '*.txt' \
        ! -name 'kernel-source-*' \
        -exec cp -a {} "$destdir/" \;

    # Orphan .asc files (e.g. CHECKSUMS.md5.asc); per-package .asc was
    # handled by copy_one_pkg.
    while IFS= read -r -d '' f; do
      case "$f" in
        *.txz.asc|*.tgz.asc) continue ;;
        *kernel-source-*) continue ;;
      esac
      cp -a "$f" "$destdir/"
    done < <(find "$srcdir" -maxdepth 1 -type f -name '*.asc' -print0)
  }

  local series_dir series
  for series_dir in "$AMOS_PRODUCTION"/*/; do
    [ -d "$series_dir" ] || continue
    series=$(basename "$series_dir")
    case "$series" in
      # extra)
      #   mkdir -p "$ISODIR/extra"
      #   copy_series "$series_dir" "$ISODIR/extra"
      #   ;;
      *)
        mkdir -p "$ISODIR/$PKGMAIN/$series"
        copy_series "$series_dir" "$ISODIR/$PKGMAIN/$series"
        ;;
    esac
  done

  local missing
  missing=$(find "$ISODIR/$PKGMAIN" -type f -name '*.txz' \
      ! -exec test -e '{}.asc' \; -print)
  if [ -n "$missing" ]; then
    echo "ERROR: .asc missing from ISO for:" >&2
    printf '  %s\n' $missing >&2
    exit 1
  fi

  if find "$ISODIR/$PKGMAIN" -name 'kernel-source-*' -print -quit 2>/dev/null | grep -q .; then
    echo "ERROR: kernel-source-* leaked into the ISO tree:" >&2
    find "$ISODIR/$PKGMAIN" -name 'kernel-source-*' >&2
    exit 1
  fi

  local pkg_count txt_count asc_count
  pkg_count=$(find "$ISODIR/$PKGMAIN" -type f -name '*.txz' | wc -l)
  txt_count=$(find "$ISODIR/$PKGMAIN" -type f -name '*.txt' 2>/dev/null | wc -l)
  asc_count=$(find "$ISODIR/$PKGMAIN" -type f -name '*.asc' 2>/dev/null | wc -l)
  echo "Copied $pkg_count packages into ISO $PKGMAIN/"
  echo "         $txt_count .txt description(s), $asc_count .asc signature(s)"
}

# --- 9. amosfeed + annode payload ---
stage_annode() {

  if [ "${INCLUDE_ANNODE_PAYLOAD:-1}" = "0" ]; then
    echo
    echo "=== Skipping Annode payload (INCLUDE_ANNODE_PAYLOAD=0 in profile) ==="
    return 0
  fi
  echo
  echo "=== Building amosfeed ==="

  local AMOSFEED_SRC="$ANNODE_INSTALL/amosfeed.c"
  local AMOSFEED_MAKE="$ANNODE_INSTALL/Makefile"
  local AMOSFEED_BIN="$ANNODE_INSTALL/amosfeed"

  [ -f "$AMOSFEED_SRC" ]  || { echo "ERROR: $AMOSFEED_SRC missing." >&2; exit 1; }
  [ -f "$AMOSFEED_MAKE" ] || { echo "ERROR: $AMOSFEED_MAKE missing." >&2; exit 1; }

  make -C "$ANNODE_INSTALL" clean >/dev/null 2>&1 || true

  if make -C "$ANNODE_INSTALL" static >/dev/null 2>&1 && [ -x "$AMOSFEED_BIN" ]; then
    echo "  built (static)"
  elif make -C "$ANNODE_INSTALL" all >/dev/null 2>&1 && [ -x "$AMOSFEED_BIN" ]; then
    echo "  built (dynamic -- static libc unavailable)"
  else
    echo "ERROR: amosfeed build failed. Re-run to see compiler output:" >&2
    echo "       make -C $ANNODE_INSTALL clean all" >&2
    exit 1
  fi

  [ -x "$AMOSFEED_BIN" ] || { echo "ERROR: $AMOSFEED_BIN not produced" >&2; exit 1; }
  echo "  $(file -b "$AMOSFEED_BIN" 2>/dev/null || echo "binary produced")"

  echo
  echo "=== Staging installer scripts to /install/annode ==="

  [ -f "$ANNODE_INSTALL/setup-annode.sh" ]   || { echo "ERROR: $ANNODE_INSTALL/setup-annode.sh missing." >&2; exit 1; }
  [ -f "$ANNODE_INSTALL/peers" ]             || { echo "ERROR: $ANNODE_INSTALL/peers missing." >&2; exit 1; }

  mkdir -p "$ISODIR/install/annode"
  cp -a "$ANNODE_INSTALL/setup-annode.sh"   "$ISODIR/install/annode/"
  cp -a "$ANNODE_INSTALL/peers"             "$ISODIR/install/annode/"
  cp -a "$AMOSFEED_BIN"                     "$ISODIR/install/annode/amosfeed"
  chmod 755 "$ISODIR/install/annode/setup-annode.sh" \
            "$ISODIR/install/annode/amosfeed"
  chmod 644 "$ISODIR/install/annode/peers"
  echo "  $(du -sh "$ISODIR/install/annode" | cut -f1) -> /install/annode/ on ISO"

  echo
  echo "=== Staging annode payload (data only) ==="
  [ -d "$ANNODE_SRC" ] || { echo "ERROR: no annode payload source at $ANNODE_SRC" >&2; exit 1; }

  mkdir -p "$ISODIR/payload/annode"
  for f in anne-node.zip annedb-latest.sql.zip; do
    [ -f "$ANNODE_SRC/$f" ] || { echo "ERROR: missing $ANNODE_SRC/$f" >&2; exit 1; }
    cp -a "$ANNODE_SRC/$f" "$ISODIR/payload/annode/"
  done
  echo "  $(du -sh "$ISODIR/payload/annode" | cut -f1) -> /payload/annode/ on ISO"

  echo
  echo "=== Signing annode payload ==="
  (
    cd "$ISODIR/payload/annode"
    find . -type f \
        ! -name 'CHECKSUMS.sha256' \
        ! -name 'CHECKSUMS.sha256.asc' \
        -print0 \
      | sort -z \
      | xargs -0 sha256sum \
      > CHECKSUMS.sha256
  )
  local payload_count
  payload_count=$(wc -l < "$ISODIR/payload/annode/CHECKSUMS.sha256")
  echo "  $payload_count entries -> /payload/annode/CHECKSUMS.sha256"

  gpg --detach-sign --armor --yes \
      --local-user "$GPG_KEY" \
      --output "$ISODIR/payload/annode/CHECKSUMS.sha256.asc" \
      "$ISODIR/payload/annode/CHECKSUMS.sha256"
  echo "  signed -> /payload/annode/CHECKSUMS.sha256.asc (key: $GPG_KEY)"
}

# --- 10. PACKAGES.TXT + package-tree CHECKSUMS.md5 ---
stage_package_manifests() {
  local PKGTXT="$ISODIR/$PKGMAIN/PACKAGES.TXT"
  : > "$PKGTXT"
  find "$ISODIR/$PKGMAIN" -type f -name '*.txz' | sort | while read -r f; do
    local fname rel csize
    fname=$(basename "$f")
    rel="./$(dirname "${f#$ISODIR/}")"
    csize=$(du -k "$f" | cut -f1)
    {
      printf 'PACKAGE NAME:  %s\n' "$fname"
      printf 'PACKAGE LOCATION:  %s\n' "$rel"
      printf 'PACKAGE SIZE (compressed):  %s K\n' "$csize"
      printf 'PACKAGE SIZE (uncompressed):  0 K\n'
      printf 'PACKAGE DESCRIPTION:\n'
      tar -xOf "$f" install/slack-desc 2>/dev/null || true
      printf '\n\n'
    } >> "$PKGTXT"
  done
  local PKGCOUNT
  PKGCOUNT=$(grep -c '^PACKAGE NAME:' "$PKGTXT" || true)
  echo "Generated ${PKGCOUNT:-0} entries in PACKAGES.TXT."

  echo
  echo "=== Generating in-ISO CHECKSUMS.md5 ==="
  (
    cd "$ISODIR/$PKGMAIN"
    find . -maxdepth 2 -type f \
        ! -name 'CHECKSUMS.md5' \
        ! -name 'CHECKSUMS.md5.asc' \
        -print0 \
      | sort -z \
      | xargs -0 md5sum \
      > CHECKSUMS.md5
  )
  local CHECKSUM_COUNT
  CHECKSUM_COUNT=$(wc -l < "$ISODIR/$PKGMAIN/CHECKSUMS.md5")
  echo "  $CHECKSUM_COUNT entries -> /$PKGMAIN/CHECKSUMS.md5"

  gpg --detach-sign --armor --yes \
      --local-user "$GPG_KEY" \
      --output "$ISODIR/$PKGMAIN/CHECKSUMS.md5.asc" \
      "$ISODIR/$PKGMAIN/CHECKSUMS.md5"
  echo "  signed -> /$PKGMAIN/CHECKSUMS.md5.asc (key: $GPG_KEY)"
}

# --- 11. EFI boot image + /EFI/BOOT tree ---
build_efi_image() {
  echo
  echo "=== Building EFI boot image ==="

  local ELILO_EFI="$ELILO_EFI_SRC"
  if [ -z "$ELILO_EFI" ] && [ -f "$BOOT/elilo.efi" ]; then
    ELILO_EFI="$BOOT/elilo.efi"
  fi
  if [ -z "$ELILO_EFI" ]; then
    local ELILO_PKG
    ELILO_PKG=$(find "$AMOS_PRODUCTION" -name 'elilo-*.txz' 2>/dev/null | head -n1)
    if [ -n "$ELILO_PKG" ]; then
      echo "  elilo package: $ELILO_PKG"
      local TMP_ELILO FOUND_EFI
      TMP_ELILO=$(mktemp -d)
      tar -xf "$ELILO_PKG" -C "$TMP_ELILO" 2>/dev/null || true
      FOUND_EFI=$(find "$TMP_ELILO" -type f -iname '*.efi' \
          ! -iname '*ia32*' ! -iname '*i386*' 2>/dev/null | head -n1)
      if [ -z "$FOUND_EFI" ]; then
        FOUND_EFI=$(find "$TMP_ELILO" -type f -iname '*.efi' 2>/dev/null | head -n1)
        if [ -n "$FOUND_EFI" ]; then
          echo "  WARNING: only found a 32-bit EFI binary ($FOUND_EFI); UEFI boot on x86_64 may fail" >&2
        fi
      fi
      if [ -n "$FOUND_EFI" ]; then
        ELILO_EFI="$FOUND_EFI"
      else
        echo "  WARNING: no .efi file inside $ELILO_PKG" >&2
        echo "  Contents:" >&2
        tar -tf "$ELILO_PKG" | sed 's/^/    /' >&2
      fi
    fi
  fi

  [ -n "$ELILO_EFI" ] && [ -f "$ELILO_EFI" ] || {
    echo "ERROR: elilo.efi not found." >&2
    echo "       Set ELILO_EFI_SRC=/path/to/elilo.efi, place one at" >&2
    echo "       boot/elilo.efi, or ensure the elilo package is" >&2
    echo "       present under \$AMOS_PRODUCTION/." >&2
    exit 1
  }
  echo "  elilo.efi source: $ELILO_EFI"

  local KERNEL_SRC="$ISODIR/isolinux/vmlinuz"
  local INITRD_SRC="$ISODIR/isolinux/initrd.img"
  [ -f "$KERNEL_SRC" ] || { echo "ERROR: $KERNEL_SRC missing." >&2; exit 1; }
  [ -f "$INITRD_SRC" ] || { echo "ERROR: $INITRD_SRC missing." >&2; exit 1; }

  local KERNEL_SIZE INITRD_SIZE ELILO_SIZE NEEDED_MIB EFI_IMG_MIB
  KERNEL_SIZE=$(stat -c %s "$KERNEL_SRC")
  INITRD_SIZE=$(stat -c %s "$INITRD_SRC")
  ELILO_SIZE=$(stat -c %s "$ELILO_EFI")

  NEEDED_MIB=$(( (KERNEL_SIZE + INITRD_SIZE + ELILO_SIZE + 16777216) / 1048576 + 1 ))
  [ "$NEEDED_MIB" -lt 32 ] && NEEDED_MIB=32
  EFI_IMG_MIB="${EFI_IMG_MIB:-$NEEDED_MIB}"
  local EFI_IMG="$ISODIR/isolinux/efi.img"

  echo "  content: vmlinuz $(numfmt --to=iec "$KERNEL_SIZE" 2>/dev/null || echo "$KERNEL_SIZE B"),"
  echo "           initrd  $(numfmt --to=iec "$INITRD_SIZE" 2>/dev/null || echo "$INITRD_SIZE B"),"
  echo "           elilo   $(numfmt --to=iec "$ELILO_SIZE" 2>/dev/null || echo "$ELILO_SIZE B")"
  echo "  image size: ${EFI_IMG_MIB} MiB"

  dd if=/dev/zero of="$EFI_IMG" bs=1M count="$EFI_IMG_MIB" status=none
  mkfs.vfat -n AMOSEFI "$EFI_IMG" >/dev/null

  export MTOOLS_SKIP_CHECK=1
  mmd -i "$EFI_IMG" ::/EFI ::/EFI/BOOT
  mcopy -i "$EFI_IMG" "$ELILO_EFI"   ::/EFI/BOOT/BOOTX64.EFI
  mcopy -i "$EFI_IMG" "$KERNEL_SRC"  ::/EFI/BOOT/vmlinuz
  mcopy -i "$EFI_IMG" "$INITRD_SRC"  ::/EFI/BOOT/initrd.img

  local ELILO_ISO_CONF="$STAGING/elilo-iso.conf"
  cat > "$ELILO_ISO_CONF" <<EOF
# AM·OS installer -- EFI boot configuration.
prompt
timeout = 5
default = AMOS

image = vmlinuz
  initrd = initrd.img
  label  = AMOS
  append = "video=$VIDEO_RES load_ramdisk=1 prompt_ramdisk=0 rw printk.time=0 quiet loglevel=3 vt.default_utf8=1"
EOF
# initcall_blacklist=init_ima
  mcopy -i "$EFI_IMG" "$ELILO_ISO_CONF" ::/EFI/BOOT/elilo.conf
  echo "  $EFI_IMG"
  echo "  EFI/BOOT/BOOTX64.EFI  <- $ELILO_EFI"
  echo "  EFI/BOOT/vmlinuz      <- $KERNEL_SRC"
  echo "  EFI/BOOT/initrd.img   <- $INITRD_SRC"
  echo "  EFI/BOOT/elilo.conf   (video=$VIDEO_RES)"

  echo
  echo
  echo "=== Providing /EFI/BOOT at the ISO9660 level ==="
  mkdir -p "$ISODIR/EFI/BOOT"
  
  # 1. We MUST copy the bootloader binary here.
  cp "$ELILO_EFI" "$ISODIR/EFI/BOOT/BOOTX64.EFI"

  # 2. We create a fallback elilo.conf pointing to /isolinux/
  cat > "$ISODIR/EFI/BOOT/elilo.conf" <<EOF
# AM·OS installer -- EFI fallback boot configuration.
prompt
timeout = 5
default = AMOS

image = /isolinux/vmlinuz
  initrd = /isolinux/initrd.img
  label  = AMOS
  append = "video=$VIDEO_RES load_ramdisk=1 prompt_ramdisk=0 rw printk.time=0 quiet loglevel=3 vt.default_utf8=1"
EOF

  echo "  /EFI/BOOT/BOOTX64.EFI"
  echo "  /EFI/BOOT/elilo.conf (points to /isolinux/)"
}


# --- 12. ISO-wide CHECKSUMS.md5 ---
gen_iso_wide_checksums() {
  echo
  echo "=== Generating CHECKSUMS.md5 over the ISO tree ==="
  local ISO_MD5="$ISODIR/CHECKSUMS.md5"
  local ISO_MD5_ASC="$ISODIR/CHECKSUMS.md5.asc"
  rm -f "$ISO_MD5" "$ISO_MD5_ASC"

  cat > "$ISO_MD5" <<'HDR'
These are the MD5 message digests for the files in this directory.
If you want to test your files, use 'md5sum' and compare the values to
the ones listed here.

To test all these files, use this command:

tail +13 CHECKSUMS.md5 | md5sum -c --quiet - | less

'md5sum' can be found in the GNU coreutils package on ftp.gnu.org in
/pub/gnu, or at any GNU mirror site.

MD5 message digest                Filename
HDR

  (
    cd "$ISODIR"
    find . -type f \
        ! -name 'CHECKSUMS.md5' \
        ! -name 'CHECKSUMS.md5.asc' \
        ! -path './isolinux/isolinux.bin' \
        -print0 \
      | sort -z \
      | xargs -0 md5sum \
      >> CHECKSUMS.md5
  )

  local ISO_MD5_COUNT
  ISO_MD5_COUNT=$(tail -n +13 "$ISO_MD5" | wc -l)
  echo "  $ISO_MD5_COUNT file(s) -> /CHECKSUMS.md5"

  gpg --detach-sign --armor --yes \
      --local-user "$GPG_KEY" \
      --output "$ISO_MD5_ASC" \
      "$ISO_MD5"
  echo "  signed -> /CHECKSUMS.md5.asc (key: $GPG_KEY)"
}

# --- 13. xorriso ---
build_iso() {
  local outiso="$1"
  echo
  echo "=== Building ISO: $outiso ==="
  cd "$REPO_DIR"




  local XORRISO_ARGS=(
    -o "$outiso"
    -R -J -V "AMOS"
    -hide-rr-moved
    -v -d -N
    -no-emul-boot -boot-load-size 4 -boot-info-table
    -b isolinux/isolinux.bin
    -c isolinux/isolinux.boot
    -isohybrid-mbr "$ISODIR/isolinux/isohdpfx.bin"
    -eltorito-alt-boot
    -e isolinux/efi.img
    -uid 0
    -gid 0
   --set_all_file_dates "$ISO_DATE"
   --modification-date="$ISO_DATE"
    -boot-load-size 0
    -no-emul-boot
    -isohybrid-gpt-basdat
    -preparer "AMOS ${RELEASE} (custom)"
    -publisher "ANNE Media"
    -A "AMOS ${RELEASE} ${ARCH}"
  )

  xorriso -as mkisofs "${XORRISO_ARGS[@]}" "$ISODIR"

  md5sum    "$outiso" > "${outiso}.md5"
  sha256sum "$outiso" > "${outiso}.sha256"

  gpg --detach-sign --armor --yes \
      --local-user "$GPG_KEY" \
      --output "${outiso}.md5.asc" "${outiso}.md5"
  gpg --detach-sign --armor --yes \
      --local-user "$GPG_KEY" \
      --output "${outiso}.sha256.asc" "${outiso}.sha256"

  echo "  ${outiso}.md5         + .asc"
  echo "  ${outiso}.sha256      + .asc"
}

# =============================================================================
# Main
# =============================================================================

echo
echo "=== Populating ISO tree (no source) ==="
mirror_repo 0
stage_boot_assets
stage_root_hash
stage_debug_key
ensure_initrd
apply_initrd
# stage_install_overlay
sign_packages
stage_packages
stage_annode
stage_package_manifests
build_efi_image
printf '%s\n' "$ISO_DATE" > "$ISODIR/.build-date"
gen_iso_wide_checksums

build_iso "$OUTISO"

if [ "$WITH_SOURCE" = "1" ]; then
  echo
  echo "=== Adding source/ and source-am/ for source ISO ==="
  for d in source source-am build overrides; do
    if [ -d "$REPO_DIR/$d" ]; then
      rm -rf "$ISODIR/$d"
      cp -a "$REPO_DIR/$d" "$ISODIR/"
      echo "  $d ($(du -sh "$REPO_DIR/$d" | cut -f1))"
    fi
  done

  echo
  echo "=== Regenerating CHECKSUMS.md5 for the source ISO ==="
  printf '%s\n' "$ISO_DATE" > "$ISODIR/.build-date"
  gen_iso_wide_checksums

  build_iso "$OUTISO_SRC"

  echo
  echo "=== Publishing source ISO's CHECKSUMS.md5 to $REPO_DIR ==="
  cp -a "$ISODIR/CHECKSUMS.md5"     "$REPO_DIR/CHECKSUMS-src.md5"
  cp -a "$ISODIR/CHECKSUMS.md5.asc" "$REPO_DIR/CHECKSUMS-src.md5.asc"
  echo "  $REPO_DIR/CHECKSUMS-src.md5"
  echo "  $REPO_DIR/CHECKSUMS-src.md5.asc"
fi

echo
echo "======================================================"
echo "Primary ISO:  $OUTISO"
echo "Size:         $(du -h "$OUTISO" | cut -f1)"
echo "MD5:          $(cut -d' ' -f1 < "${OUTISO}.md5")"
echo "SHA256:       $(cut -d' ' -f1 < "${OUTISO}.sha256")"
echo "Signer:       $GPG_KEY"
if [ "$WITH_SOURCE" = "1" ]; then
  echo
  echo "Source ISO:   $OUTISO_SRC"
  echo "Size:         $(du -h "$OUTISO_SRC" | cut -f1)"
  echo "MD5:          $(cut -d' ' -f1 < "${OUTISO_SRC}.md5")"
  echo "SHA256:       $(cut -d' ' -f1 < "${OUTISO_SRC}.sha256")"
fi
echo "======================================================"
echo
cat <<EOF
Boot notes:
  - BIOS and EFI are both supported. The ISO picks the right path
    automatically.
  - On UEFI systems, ensure Secure Boot is off; the bootloader is
    not signed with a Microsoft key.
  - Video mode defaults to ${VIDEO_RES}. Override at boot time with
    a different "video=" parameter on the isolinux or elilo cmdline
    if the console resolution is unsupported.
EOF