#!/bin/bash
#
# build-initrd.sh -- assemble the AM·OS installer initrd from AM·OS packages.
#
# Inputs, all from $AMOS_PRODUCTION:
#   z/busybox-*.txz
#   a/kernel-generic-*.txz          kernel + module tree
#   a/kernel-firmware-*.txz         firmware blobs (curated subset)
#   a/<tool>-*.txz, n/<tool>-*.txz  real binaries install.sh requires
#
# Plus AM·OS sources under initrd-src/:
#   initrd-src/etc/                 -> /etc/ in the initrd
#   initrd-src/files/               -> / in the initrd (root-level files)
#
# Files under initrd-src/ are copied as-is by the overlay step near the
# end of this script. Edit them there; this script does not synthesise
# any of them.

set -eu
umask 022

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
AMOS_PRODUCTION="${AMOS_PRODUCTION:-$SCRIPT_DIR/../amos64}"
INITRD_SRC="${INITRD_SRC:-$SCRIPT_DIR/initrd-src}"
OUT_INITRD="$SCRIPT_DIR/initrd.img"
GPG_PUBKEY="${GPG_PUBKEY:-$SCRIPT_DIR/../AMOS-GPG-KEY}"
ISO_PROFILE=$1

BUSYBOX_PKG_GLOB="${BUSYBOX_PKG_GLOB:-busybox-*.txz}"
KERNEL_PKG_GLOB="${KERNEL_PKG_GLOB:-kernel-generic-*.txz}"
FIRMWARE_PKG_GLOB="${FIRMWARE_PKG_GLOB:-kernel-firmware-[0-9]*.txz}"

NET_FIRMWARE_PREFIXES=(
    3com acenic adaptec bnx tigon e100 sun kaweth cxgb3 rtl_nic
    qed ql2 qlogic isci
)

MODULE_PRUNE=(
    kernel/drivers/gpu/drm/amd
    kernel/drivers/gpu/drm/radeon
    kernel/drivers/gpu/drm/nouveau
    kernel/drivers/gpu/drm/i915
    kernel/drivers/gpu/drm/xe
    kernel/drivers/gpu/drm/msm
    kernel/drivers/gpu/drm/exynos
    kernel/drivers/gpu/drm/tegra
    kernel/drivers/gpu/drm/mediatek
    kernel/drivers/gpu/drm/rockchip
    kernel/drivers/gpu/drm/vc4
    kernel/drivers/gpu/drm/v3d
    kernel/drivers/gpu/drm/vkms
    kernel/drivers/gpu/drm/panel
    kernel/drivers/gpu/drm/bridge
    kernel/drivers/sound
    kernel/drivers/media
    kernel/drivers/infiniband
    kernel/drivers/thunderbolt
    kernel/drivers/greybus
    kernel/drivers/comedi
    kernel/drivers/iio
    kernel/drivers/hwmon
    kernel/drivers/watchdog
    kernel/drivers/pinctrl
    kernel/drivers/leds
    kernel/drivers/net/bluetooth
    kernel/drivers/staging
)

# Packages we extract in full. Only binaries in TOOL_BINARIES end up in
# the initrd, but every .so these packages ship becomes available to
# the package-aware library fixpoint below.
TOOL_PKGS=(
    dropbear
    elfutils
    # strace
    aaa_glibc-solibs
    acl
    attr
    bzip2
    efivar
    file
    glibc-zoneinfo
    gmp
    inih
    json-c
    libaio
    libassuan
    libgcrypt
    libgpg-error
    npth
    lzo
    mpfr
    popt
    readline
    userspace-rcu
    zlib
    zstd
    # sqlite
    libusb
    lzlib
    bash
    parted
    kmod
    e2fsprogs
    util-linux
    dialog
    pkgtools
    cryptsetup
    lvm2
    dosfstools
    efibootmgr
    eudev
    iproute2
    gawk
    openssl
    openssl-solibs
    libksba
    gnupg2
    gnupg
    coreutils
    tar
    xz
    gzip
    ncurses
    xfsprogs
    btrfs-progs
    nano
    pciutils
    usbutils
    hwdata
    dmidecode
    smartmontools
    nvme-cli
    keyutils
    less
    kbd
    # icu4c
    sed
    grep
    findutils
    # binutils
    shadow
    which
    # Libraries required by binaries above.
    pcre2
    libcap
    libcap-ng
    pam
    libtirpc
    libmnl
    fbv
    libpng
    libjpeg-turbo
    liburing
    libarchive
    libxml2
    lz4
)

# Real binaries staged into the initrd. Every name here is resolved via
# find_tool_src, which finds the real file in the extracted package
# tree (dereferencing intra-package symlinks and versioned names). The
# de-shadow step further down removes any busybox applet symlink whose
# name now also has a real binary on PATH.
#
# Multicall dispatchers (kmod, dropbearmulti, lvm, mke2fs, mkfs.fat)
# are listed only under their canonical name; their alias symlinks are
# synthesised after the copy pass.
TOOL_BINARIES=(
    # --- shell and packaging ---
    bash
    tar
    xz
    gzip
    bzip2
    chroot
    installpkg
    upgradepkg
    removepkg
    sed
    grep
    find
    gawk

    # --- block devices / partitioning ---
    parted
    partprobe
    wipefs
    blockdev
    lsblk
    blkid
    fdisk
    sfdisk
    cfdisk
    losetup
    dmsetup
    mkswap
    fallocate
    blkdiscard
    fstrim
    fsfreeze

    # --- filesystems ---
    mke2fs
    e2fsck
    tune2fs
    dumpe2fs
    debugfs
    resize2fs
    mkfs.fat
    mkfs.xfs
    xfs_repair
    xfs_db
    mkfs.btrfs
    btrfs

    # --- LUKS / LVM ---
    cryptsetup
    lvm

    # --- kernel module management ---
    kmod

    # --- udev / EFI ---
    udevadm
    efibootmgr

    # --- crypto / signing ---
    openssl
    gpg
    gpgconf
    gpg-agent
    gpg-connect-agent
    keyboxd

    # --- hardware survey ---
    lspci
    lsusb
    dmidecode
    nvme
    smartctl

    # --- coreutils ---
    cat
   # chmod hmm with this we get error Function not implemented (ENOSYS) because our chmod binary inside was compiled against a new version of glibc/coreutils. It tries to use a >=6.6 Linux kernel system call called fchmodat2 Many hosting providers rescue kernel is older than 6.6. Normally, glibc should gracefully fall back to the older fchmodat system call, but in this initrd environment, that fallback is failing. We could possibly rebuild glibc with an older minimum kernel target eg --enable-kernel=5.15 to force the fallback code to be included, allowing chmod to work on all kernels. No need to do this if the busybox chmod will suffice in all envinroments. Commented out for now. TBC.
    chown
    cp
    cut
    date
    dd
    df
    dirname
    basename
    du
    env
    expr
    head
    id
    # install same as chmod above
    ln
    ls
    md5sum
    mkdir
    mktemp
    mv
    nproc
    printf
    pwd
    readlink
    realpath
    rm
    rmdir
    seq
    sha1sum
    sha256sum
    sha512sum
    sleep
    sort
    stat
    sync
    tail
    tee
    test
    touch
    tr
    true
    false
    truncate
    uname
    uniq
    wc
    paste
    numfmt
    # --- util-linux ---
    mount
    umount
    mountpoint
    findmnt
    dmesg
    hexdump
    more
    nsenter
    unshare
    setpriv
    setarch
    taskset
    flock
    ionice
    renice
    switch_root

    # --- acl / attr ---
    getfacl
    setfacl
    getfattr
    setfattr
    lsattr
    chattr

    # --- shadow ---
    su
    login
    passwd
    chpasswd
    useradd
    usermod
    userdel
    groupadd
    groupmod
    groupdel

    # --- misc ---
    which
    file
    less
    nano
    dialog

    # --- compression helpers ---
    gunzip
    zcat
    bzcat
    bunzip2
    unxz
    xzcat

   # readelf
    # strings
    # --- multicall base (aliases synthesised below) ---
    dropbearmulti
     # --- iproute2 ---
    ip
    ss
    fbv
)

die() { echo "ERROR: $*" >&2; exit 1; }
log() { echo ">>> $*"; }

command -v readelf >/dev/null \
    || die "readelf (binutils) required on the build host"

WORK=$(mktemp -d /tmp/amos-initrd.XXXXXX)
cleanup() { cd /; rm -rf "$WORK"; }
trap cleanup EXIT

mkdir -p "$WORK"/{bin,sbin,etc,etc/profile.d,proc,sys,dev,tmp,root,mnt/cdrom,lib/modules,lib/firmware,lib64,usr/bin,usr/sbin,usr/lib64,usr/lib,usr/libexec,usr/local/bin,var/lib,run,run/cryptsetup,run/lock,run/udev,run/udev/data,run/lvm,run/lock/lvm}
chmod 1777 "$WORK/tmp"
chmod 755 "$WORK/run" "$WORK/run/lock" "$WORK/run/udev" "$WORK/run/udev/data"
chmod 700 "$WORK/run/cryptsetup"
chmod 755 "$WORK/run/lvm" "$WORK/run/lock/lvm"

# ============================================================
# GPG configuration for the initrd
# ============================================================
# GnuPG 2.4+ tries to launch keyboxd, which requires SQLite and a
# running background daemon. This fails in a minimal initrd.
# Creating common.conf with "#use-keyboxd" forces gpg to use the
# classic file-based keyring and bypasses the daemon entirely.

log "configuring gpg for initrd"
mkdir -p "$WORK/root/.gnupg"
chmod 700 "$WORK/root"
chmod 700 "$WORK/root/.gnupg"
echo "#use-keyboxd" > "$WORK/root/.gnupg/common.conf"
chmod 644 "$WORK/root/.gnupg/common.conf"

# busybox
# ============================================================
BUSYBOX_PKG=$(find "$AMOS_PRODUCTION" -name "$BUSYBOX_PKG_GLOB" 2>/dev/null \
    | sort -V | tail -n1)
[ -n "$BUSYBOX_PKG" ] || die "no $BUSYBOX_PKG_GLOB under $AMOS_PRODUCTION"
log "busybox: $BUSYBOX_PKG"

TMP_BB=$(mktemp -d)
tar -xf "$BUSYBOX_PKG" -C "$TMP_BB"
BUSYBOX_BIN=$(find "$TMP_BB" -name busybox -type f -print -quit)
[ -n "$BUSYBOX_BIN" ] || die "no busybox binary in $BUSYBOX_PKG"
cp "$BUSYBOX_BIN" "$WORK/bin/busybox"
chmod 755 "$WORK/bin/busybox"
rm -rf "$TMP_BB"

# Every applet gets a symlink. They cost nothing (they are symlinks)
# and provide a fallback for anything the real-binary pass misses.
# The de-shadow step below removes any whose name is also provided by
# a real binary on PATH.
log "creating applet symlinks"
applet_count=0
while IFS= read -r applet; do
    [ "$applet" = "busybox" ] && continue
    ln -sf busybox "$WORK/bin/$applet"
    applet_count=$((applet_count + 1))
done < <("$WORK/bin/busybox" --list)
log "  $applet_count applet(s)"


# Override the power-management applets with wrappers.
#
# Two reasons this is a wrapper and not the busybox applet:
#
#   1. Busybox reboot/poweroff/halt send a signal to PID 1 by default,
#      and PID 1 is /init, a bash script that ignores SIGTERM. The
#      kernel's reboot(2) syscall is never reached. `-f` calls it
#      directly, which is what an interactive reboot from the installer
#      shell needs.
#
#   2. When invoked over the debug SSH session, killing dropbear before
#      the power operation would SIGHUP this shell and kill the operation
#      with it. The setsid child survives.
#
# rm -f before the redirect is essential: the applet symlinks were
# installed above, and `cat >` would otherwise follow the symlink and
# overwrite $WORK/bin/busybox itself.

for pm in reboot poweroff halt; do
    rm -f "$WORK/bin/$pm"
    cat > "$WORK/bin/$pm" <<EOF
#!/bin/sh
# Wrapper for $pm that bypasses PID 1 and survives the dropbear teardown.
echo "System going down for $pm..."
sync

# Launch the power operation in a detached session so it survives the
# SIGHUP that will hit this shell when dropbear is killed below. The
# short sleep gives the host's ssh client time to see dropbear's FIN
# and exit before reboot(2) tears the network down. No-op on the
# console; the setsid child reboots in either case.
setsid sh -c 'sleep 2; sync; busybox $pm -f || echo b > /proc/sysrq-trigger' \\
    </dev/null >/dev/null 2>&1 &

# Close any debug SSH session cleanly. The host's ssh client sees FIN
# instead of hanging in ESTABLISHED waiting for slirp to notice the
# guest's TCP stack is gone.
pkill -x dropbear 2>/dev/null || true

# If we are in an SSH session, we will be killed by SIGHUP here when
# dropbear exits. The setsid child carries on.
sleep 3
EOF
    chmod 755 "$WORK/bin/$pm"
done
log "  power-management wrappers installed (reboot, poweroff, halt)"

# ============================================================
# tool packages -- extract, then run doinst.sh to materialize
# .new files and create version symlinks
# ============================================================
run_doinst() {
    local root="$1"
    local script="$root/install/doinst.sh"
    [ -f "$script" ] || return 0
    (
        cd "$root"
        config() {
            local new="$1" old
            old="${new%.new}"
            [ -f "$new" ] || return 0
            if [ ! -f "$old" ]; then
                mv "$new" "$old"
            else
                rm -f "$new"
            fi
        }
        preserve_perms() { :; }
        # shellcheck disable=SC1090
        . "$script"
    ) >/dev/null 2>&1 || true
}

log "extracting tool packages"
TMP_PKGS=$(mktemp -d)
extracted=0
missing_pkgs=()
PKG_DIRS=()
for name in "${TOOL_PKGS[@]}"; do
    pkg=$(find "$AMOS_PRODUCTION" -name "${name}-[0-9]*.t?z" 2>/dev/null \
        | sort -V | tail -n1)
    if [ -z "$pkg" ]; then
        missing_pkgs+=("$name")
        continue
    fi
    pdst="$TMP_PKGS/$name"
    mkdir -p "$pdst"
    if ! tar -xf "$pkg" -C "$pdst" 2>/dev/null; then
        log "  ! $name (extract failed)"
        continue
    fi
    run_doinst "$pdst"
    PKG_DIRS+=("$pdst")
    extracted=$((extracted + 1))
done
log "  extracted $extracted package(s)"
[ ${#missing_pkgs[@]} -gt 0 ] && log "  not found: ${missing_pkgs[*]}"

# ------------------------------------------------------------
# extract_one_lib <pkgname> <libpath> <soname>
#
# Pull a single shared library out of a large package without
# extracting the whole thing, and stage it under
#   $TMP_PKGS/.runtime-<pkgname>/<libpath>
# so the SONAME index and the fixpoint that follow see it like any
# other extracted file. Appends the synthetic dir to PKG_DIRS.
#
# Use case: libstdc++.so.6 and libgcc_s.so.1 live inside gcc-g++ and
# gcc respectively, each ~100 MB. We want the two libraries, not the
# compilers.
# ------------------------------------------------------------
extract_one_lib() {
    local pkgname="$1" libpath="$2"
    local pkg real synthetic

    [ -e "$WORK/$libpath" ] && return 0

    pkg=$(find "$AMOS_PRODUCTION" -name "${pkgname}-[0-9]*.t?z" 2>/dev/null \
        | sort -V | tail -n1)
    [ -n "$pkg" ] || die "package $pkgname not found for $libpath"

    local filelist=$(tar -tf "$pkg" 2>/dev/null | sed 's|^\./||')

    # Strip the .0 or .78 from the end to get the base name
    # e.g., usr/lib64/libsqlite3.so.0 -> usr/lib64/libsqlite3.so
    local base_path="${libpath%.*}"

    # Find the real versioned file (e.g. libsqlite3.so.3.54.1)
    real=$(echo "$filelist" \
        | awk -v prefix="${base_path}." '
            index($0, prefix) == 1 {
                rest = substr($0, length(prefix) + 1)
                if (rest ~ /^[0-9][0-9.]*$/) print
            }' \
        | sort -V | tail -n1)

    if [ -z "$real" ]; then
        if echo "$filelist" | grep -qx "$libpath"; then
            real="$libpath"
        else
            die "$libpath or ${base_path}.* not found in $pkgname package"
        fi
    fi

    synthetic="$TMP_PKGS/.runtime-$pkgname"
    mkdir -p "$synthetic/$(dirname "$libpath")"
    
    # Extract the real file
    if ! tar -xf "$pkg" -C "$synthetic" "$real" 2>/dev/null && \
       ! tar -xf "$pkg" -C "$synthetic" "./$real" 2>/dev/null; then
        die "failed to extract $real from $pkg"
    fi

    if [ ! -f "$synthetic/$real" ]; then
        die "$real was not extracted as a regular file from $pkg"
    fi

    # Create the symlink manually if it's not in the tarball
    if [ "$real" != "$libpath" ]; then
        if ! echo "$filelist" | grep -qx "$libpath"; then
            ln -sf "$(basename "$real")" "$synthetic/$libpath"
        fi
    fi

    PKG_DIRS+=("$synthetic")
    log "    + $real (from $pkgname, staged for library index)"
    return 0
}

# Runtime libraries inside huge packages, staged before the index is
# built so the fixpoint resolves them and walks their own dependencies.
extract_one_lib gcc     usr/lib64/libgcc_s.so.1
extract_one_lib gcc-g++ usr/lib64/libstdc++.so.6
extract_one_lib sqlite usr/lib64/libsqlite3.so.0
extract_one_lib icu4c  usr/lib64/libicui18n.so.78
extract_one_lib icu4c  usr/lib64/libicuuc.so.78
extract_one_lib icu4c  usr/lib64/libicudata.so.78
# ------------------------------------------------------------
# find_tool_src <name>
#
# Locate a binary in the extracted package trees.
#
# Search order, per package:
#   1. Real file at bin/ usr/bin/ sbin/ usr/sbin/ usr/libexec/ libexec/
#   2. Symlink at one of those, whose target resolves (via readlink -f)
#      to a real file *inside the same package tree*. Anything that
#      resolves outside the tree -- typically an absolute symlink that
#      only becomes valid after install, like dropbear's
#      sbin/dropbear -> /bin/dropbearmulti -- is ignored.
#
# Output (single line, space-separated, no spaces in paths):
#   "exact <path>"
#   "resolved <link> <target>"
#
# Returns non-zero if nothing was found.
# ------------------------------------------------------------
find_tool_src() {
    local name="$1" pdst sub c target rel

    for pdst in "${PKG_DIRS[@]}"; do
        for sub in bin usr/bin sbin usr/sbin usr/libexec libexec; do
            c="$pdst/$sub/$name"
            [ -e "$c" ] || continue

            if [ -f "$c" ] && [ ! -L "$c" ]; then
                printf 'exact %s\n' "$c"
                return 0
            fi

            if [ -L "$c" ]; then
                target=$(readlink -f "$c" 2>/dev/null || true)
                [ -n "$target" ] && [ -f "$target" ] || continue
                rel="${target#$pdst/}"
                [ "$rel" = "$target" ] && continue    # escaped the tree
                printf 'resolved %s %s\n' "$c" "$target"
                return 0
            fi
        done
    done
    return 1
}

log "copying tool binaries"
copied_bins=()
missing_bins=()
for name in "${TOOL_BINARIES[@]}"; do
    if ! out=$(find_tool_src "$name"); then
        missing_bins+=("$name")
        continue
    fi

    read -r kind a b <<< "$out"

    case "$kind" in
    exact)
        src="$a"
        rel="${src#$TMP_PKGS/}"; rel="${rel#*/}"
        dst="$WORK/$rel"
        mkdir -p "$(dirname "$dst")"
        rm -f "$dst"
        cp -aL "$src" "$dst"
        chmod 755 "$dst"
        copied_bins+=("$dst")
        ;;

    resolved)
        link="$a"
        target="$b"
        rel_link="${link#$TMP_PKGS/}";     rel_link="${rel_link#*/}"
        rel_target="${target#$TMP_PKGS/}"; rel_target="${rel_target#*/}"
        dst_link="$WORK/$rel_link"
        dst_target="$WORK/$rel_target"

        mkdir -p "$(dirname "$dst_target")"
        if [ ! -f "$dst_target" ]; then
            cp -aL "$target" "$dst_target"
            chmod 755 "$dst_target"
            copied_bins+=("$dst_target")
        fi
        mkdir -p "$(dirname "$dst_link")"
        rm -f "$dst_link"
        ln -s "$(basename "$dst_target")" "$dst_link"
        copied_bins+=("$dst_link")
        ;;
    esac
done
log "  ${#copied_bins[@]} binary/binaries"
[ ${#missing_bins[@]} -gt 0 ] && log "  not in packages: ${missing_bins[*]}"

# ---- pkgtools helper tree ----
PKGTOOLS_PKG=$(find "$AMOS_PRODUCTION" -name 'pkgtools-*.t?z' 2>/dev/null \
    | sort -V | tail -n1)
if [ -n "$PKGTOOLS_PKG" ]; then
    TMP_PT=$(mktemp -d)
    tar -xf "$PKGTOOLS_PKG" -C "$TMP_PT"
    if [ -d "$TMP_PT/var/lib/pkgtools" ]; then
        cp -a "$TMP_PT/var/lib/pkgtools" "$WORK/var/lib/"
        log "  pkgtools helper tree -> /var/lib/pkgtools"
    fi
    rm -rf "$TMP_PT"
fi

# ---- terminfo ----
TERM_ROOT=$(find "$TMP_PKGS" -maxdepth 5 -type d -path '*/usr/share/terminfo' -print -quit)
if [ -n "$TERM_ROOT" ]; then
    mkdir -p "$WORK/usr/share/terminfo"
    cp -aL "$TERM_ROOT/." "$WORK/usr/share/terminfo/"
    log "  terminfo -> /usr/share/terminfo"
fi

# ---- udev rules ----
udev_rule_dirs=0
for pdst in "${PKG_DIRS[@]}"; do
    for rd in lib/udev usr/lib/udev etc/udev etc/modprobe.d; do
        [ -d "$pdst/$rd" ] || continue
        mkdir -p "$WORK/$rd"
        cp -a "$pdst/$rd/." "$WORK/$rd/"
        udev_rule_dirs=$((udev_rule_dirs + 1))
    done
done
log "  udev: $udev_rule_dirs dir(s) copied from tool packages"

# ---- pci.ids / usb.ids ----
HWDATA_DIR=$(find "$TMP_PKGS" -maxdepth 5 -type d -path '*/usr/share/hwdata' -print -quit)
if [ -n "$HWDATA_DIR" ]; then
    mkdir -p "$WORK/usr/share/hwdata"
    for base in pci.ids usb.ids; do
        if [ -f "$HWDATA_DIR/$base" ]; then
            cp -a "$HWDATA_DIR/$base" "$WORK/usr/share/hwdata/"
        elif [ -f "$HWDATA_DIR/$base.gz" ]; then
            gzip -dc "$HWDATA_DIR/$base.gz" > "$WORK/usr/share/hwdata/$base"
        fi
    done
    mkdir -p "$WORK/usr/share/misc"
    ln -sf ../hwdata/pci.ids "$WORK/usr/share/misc/pci.ids"
    ln -sf ../hwdata/usb.ids "$WORK/usr/share/misc/usb.ids"
    log "  hwdata ids -> /usr/share/hwdata (+ /usr/share/misc symlinks)"
fi

# ---- file(1) magic database ----
FILE_MAGIC=$(find "$TMP_PKGS" -maxdepth 6 -type f -name 'magic.mgc' -print -quit 2>/dev/null)
if [ -n "$FILE_MAGIC" ]; then
    mkdir -p "$WORK/usr/share/misc"
    cp -a "$FILE_MAGIC" "$WORK/usr/share/misc/magic.mgc"
    log "  file magic database -> /usr/share/misc/magic.mgc"
fi

# ---- keyboard maps ----
KBD_DIR=$(find "$TMP_PKGS" -maxdepth 5 -type d -path '*/usr/share/kbd' -print -quit)
if [ -n "$KBD_DIR" ]; then
    mkdir -p "$WORK/usr/share/kbd"
    cp -a "$KBD_DIR/." "$WORK/usr/share/kbd/"
    n_maps=$(find "$WORK/usr/share/kbd/keymaps" -name '*.map.gz' 2>/dev/null | wc -l)
    log "  kbd keymaps -> /usr/share/kbd ($n_maps maps)"
fi

# Extract pre-compiled C.utf8 locale for installer UI
I18N_PKG=$(find "$AMOS_PRODUCTION" -name "glibc-i18n-[0-9]*.t?z" 2>/dev/null | sort -V | tail -n1)
if [ -n "$I18N_PKG" ]; then
    log "extracting C.utf8 locale from glibc-i18n"
    mkdir -p "$WORK/usr/lib64/locale"
    tar -xf "$I18N_PKG" -C "$WORK" usr/lib64/locale/C.utf8 2>/dev/null || \
        log "  WARN: could not extract C.utf8 from $I18N_PKG"
fi
# ---- timezone table ----
# The wizard's ui_timezone reads zone1970.tab to build its menu.
# Only the table is needed; the individual zone files are provided
# by the target's own glibc-zoneinfo package and are not read by
# the installer at any point.
ZONE_TAB=$(find "$TMP_PKGS" -maxdepth 6 -type f \
    -path '*/usr/share/zoneinfo/zone1970.tab' -print -quit)
if [ -n "$ZONE_TAB" ]; then
    mkdir -p "$WORK/usr/share/zoneinfo"
    cp -a "$ZONE_TAB" "$WORK/usr/share/zoneinfo/"
    log "  zone1970.tab -> /usr/share/zoneinfo/zone1970.tab"
else
    log "  WARN: zone1970.tab not found in glibc-zoneinfo"
fi

# ---- LVM multicall ----
LVM_BIN=$(find "$WORK" -type f -name lvm -print -quit)
if [ -n "$LVM_BIN" ] && [ -x "$LVM_BIN" ]; then
    LVM_DIR=$(dirname "$LVM_BIN")
    lvm_symlinks=0
    for cmd in pvcreate pvchange pvremove pvscan pvdisplay pvs pvmove \
               vgcreate vgchange vgremove vgscan vgdisplay vgs \
               vgextend vgreduce vgmerge vgsplit vgrename vgexport vgimport \
               lvcreate lvchange lvremove lvscan lvdisplay lvs \
               lvextend lvreduce lvrename lvresize \
               vgmknodes; do
        ln -sf lvm "$LVM_DIR/$cmd"
        lvm_symlinks=$((lvm_symlinks + 1))
    done
    log "  $lvm_symlinks LVM symlink(s) -> $LVM_DIR"
fi

# ---- dropbear multicall ----
DBM_BIN=$(find "$WORK" -type f -name dropbearmulti -print -quit)
if [ -n "$DBM_BIN" ]; then
    DBM_DIR=$(dirname "$DBM_BIN")
    for cmd in dropbear dropbearkey dropbearconvert; do
        ln -sf dropbearmulti "$DBM_DIR/$cmd"
    done
    log "  dropbearmulti -> $DBM_DIR/{dropbear,dropbearkey,dropbearconvert}"
fi

# ---- kmod multicall ----
KMOD_BIN=$(find "$WORK" -type f -name kmod -print -quit)
if [ -n "$KMOD_BIN" ]; then
    KMOD_DIR=$(dirname "$KMOD_BIN")
    for cmd in modprobe insmod rmmod lsmod modinfo depmod; do
        ln -sf kmod "$KMOD_DIR/$cmd"
    done
    log "  kmod multicall: $KMOD_DIR/{modprobe,insmod,rmmod,lsmod,modinfo,depmod}"
fi

# ---- e2fsprogs mkfs aliases ----
MKE2FS_BIN=$(find "$WORK" -type f -name mke2fs -print -quit)
if [ -n "$MKE2FS_BIN" ]; then
    MKE2FS_DIR=$(dirname "$MKE2FS_BIN")
    for cmd in mkfs.ext2 mkfs.ext3 mkfs.ext4; do
        ln -sf mke2fs "$MKE2FS_DIR/$cmd"
    done
    log "  e2fsprogs aliases: $MKE2FS_DIR/mkfs.ext[234]"
fi

# ---- dosfstools aliases ----
MKFSFAT_BIN=$(find "$WORK" -type f -name mkfs.fat -print -quit)
if [ -n "$MKFSFAT_BIN" ]; then
    MKFSFAT_DIR=$(dirname "$MKFSFAT_BIN")
    for cmd in mkfs.vfat mkfs.msdos; do
        ln -sf mkfs.fat "$MKFSFAT_DIR/$cmd"
    done
    log "  dosfstools aliases: $MKFSFAT_DIR/mkfs.vfat"
fi

# ---- awk -> gawk ----
GAWK_BIN=$(find "$WORK" \( -type f -o -type l \) -name gawk -print -quit)
if [ -n "$GAWK_BIN" ]; then
    GAWK_DIR=$(dirname "$GAWK_BIN")
    rm -f "$GAWK_DIR/awk"
    ln -sf gawk "$GAWK_DIR/awk"
    log "  $GAWK_DIR/awk -> gawk"
fi

# ---- /bin/sh -> bash ----
BASH_BIN=$(find "$WORK" -type f -name bash -print -quit)
if [ -n "$BASH_BIN" ]; then
    BASH_DIR=$(dirname "$BASH_BIN")
    ln -sf bash "$BASH_DIR/sh"
    log "  $BASH_DIR/sh -> bash"
fi

# ---- de-shadow busybox applets ----
# Runs after all real-binary staging and multicall symlink creation so
# each alternative is visible when tested. Removes any /bin/<name>
# -> busybox symlink that now has a real implementation on PATH.
deshadowed=0
for link in "$WORK/bin"/*; do
    [ -L "$link" ] || continue
    [ "$(readlink "$link")" = "busybox" ] || continue
    name=$(basename "$link")
    for alt in "$WORK/usr/bin/$name" "$WORK/usr/sbin/$name" "$WORK/sbin/$name"; do
        if [ -x "$alt" ]; then
            rm -f "$link"
            deshadowed=$((deshadowed + 1))
            break
        fi
    done
done
log "  $deshadowed busybox applet(s) removed in favour of real binaries"

# ============================================================
# shared library fixpoint (package-aware)
# ============================================================
log "resolving shared library dependencies (package-aware)"

declare -A LIB_INDEX
index_count=0
for pdst in "${PKG_DIRS[@]}"; do
    while IFS= read -r -d '' lib; do
        soname=$(readelf -d "$lib" 2>/dev/null \
            | awk '/\(SONAME\)/ { gsub(/[\[\]]/,"",$NF); print $NF; exit }')
        [ -n "$soname" ] || soname=$(basename "$lib")

        if [ -n "${LIB_INDEX[$soname]:-}" ]; then
            continue
        fi
        LIB_INDEX["$soname"]="$lib"
        index_count=$((index_count + 1))
    done < <(find "$pdst" \( -type f -o -type l \) -name '*.so*' -print0 2>/dev/null)
done
log "  soname index: $index_count entries"

elf_needed() {
    readelf -d "$1" 2>/dev/null \
        | awk '/\(NEEDED\)/ { gsub(/[\[\]]/,"",$NF); print $NF }'
}

declare -A seen_libs
total_libs=0
missing_libs=()
declare -A missing_by

queue=("${copied_bins[@]}")
while [ ${#queue[@]} -gt 0 ]; do
    next_queue=()
    for f in "${queue[@]}"; do
        [ -f "$f" ] || continue
        while IFS= read -r soname; do
            [ -n "$soname" ] || continue
            [ -n "${seen_libs[$soname]:-}" ] && continue
            seen_libs["$soname"]=1

            src="${LIB_INDEX[$soname]:-}"
            if [ -z "$src" ]; then
                missing_libs+=("$soname")
                missing_by["$soname"]="$(basename "$f")"
                continue
            fi

            rel="${src#$TMP_PKGS/}"
            rel="${rel#*/}"
            dst="$WORK/$rel"

            mkdir -p "$(dirname "$dst")"
            rm -f "$dst"
            cp -aL "$src" "$dst"

            base=$(basename "$src")
            if [ "$base" != "$soname" ]; then
                ln -sf "$base" "$WORK/$(dirname "$rel")/$soname"
            fi

            total_libs=$((total_libs + 1))
            next_queue+=("$dst")
        done < <(elf_needed "$f")
    done
    queue=("${next_queue[@]}")
done

log "  $total_libs librar(y|ies) copied from packages"
if [ ${#missing_libs[@]} -gt 0 ]; then
    log "  WARN: sonames not found in any package (first requester shown):"
    for m in "${missing_libs[@]}"; do
        log "    $m  <- ${missing_by[$m]}"
    done
    die "add the missing provider packages to TOOL_PKGS"
fi

# ---- Dynamic linker ----
LINKER_SRC=$(find "$TMP_PKGS" -maxdepth 5 -type f \
    -path '*/lib64/ld-linux-x86-64.so.2' -print -quit 2>/dev/null)
[ -n "$LINKER_SRC" ] || LINKER_SRC=$(find "$TMP_PKGS" -maxdepth 5 -type f \
    -path '*/lib/ld-linux-x86-64.so.2' -print -quit 2>/dev/null)

if [ -n "$LINKER_SRC" ]; then
    rel="${LINKER_SRC#$TMP_PKGS/}"
    rel="${rel#*/}"
    dst="$WORK/$rel"
    mkdir -p "$(dirname "$dst")"
    cp -aL "$LINKER_SRC" "$dst"
    log "  + $rel (from package)"
else
    log "  WARN: ld-linux-x86-64.so.2 not found in any package"
fi

cat > "$WORK/etc/ld.so.conf" <<'LD'
/lib64
/usr/lib64
/lib
/usr/lib
LD
if command -v ldconfig >/dev/null; then
    ldconfig -r "$WORK" 2>/dev/null \
        || log "  WARN: ldconfig reported errors"
fi

rm -rf "$TMP_PKGS"

# ============================================================
# kernel modules
# ============================================================
KERNEL_PKG=$(find "$AMOS_PRODUCTION" -name "$KERNEL_PKG_GLOB" 2>/dev/null \
    | sort -V | tail -n1)
[ -n "$KERNEL_PKG" ] || die "no $KERNEL_PKG_GLOB under $AMOS_PRODUCTION"
log "kernel: $KERNEL_PKG"

TMP_K=$(mktemp -d)
tar -xf "$KERNEL_PKG" -C "$TMP_K"

MODROOT=$(find "$TMP_K" -maxdepth 4 -type d \
    -path '*/lib/modules/*' -print -quit 2>/dev/null)
[ -n "$MODROOT" ] || die "no lib/modules/<ver> in $KERNEL_PKG"
KVER=$(basename "$MODROOT")
log "kernel version: $KVER"

MODDST="$WORK/lib/modules/$KVER"
cp -a "$MODROOT" "$MODDST"
before_size=$(du -sm "$MODDST" | cut -f1)
log "  copied: ${before_size}M"

log "pruning module tree"
pruned=0
for p in "${MODULE_PRUNE[@]}"; do
    if [ -e "$MODDST/$p" ]; then
        rm -rf "$MODDST/$p"
        pruned=$((pruned + 1))
    fi
done
after_size=$(du -sm "$MODDST" | cut -f1)
log "  pruned: ${before_size}M -> ${after_size}M ($pruned entries)"

# ============================================================
# firmware
# ============================================================
FIRMWARE_PKG=$(find "$AMOS_PRODUCTION" -name "$FIRMWARE_PKG_GLOB" 2>/dev/null \
    | sort -V | tail -n1)
if [ -n "$FIRMWARE_PKG" ]; then
    log "firmware: $FIRMWARE_PKG"
    TMP_FW=$(mktemp -d)
    tar -xf "$FIRMWARE_PKG" -C "$TMP_FW"
    FWSRC=$(find "$TMP_FW" -maxdepth 5 -type d -path '*/lib/firmware' -print -quit)
    if [ -n "$FWSRC" ]; then
        copy_firmware_prefix() {
            local prefix="$1" matched=0
            shopt -s nullglob
            for f in "$FWSRC/${prefix}"*; do
                [ -e "$f" ] || continue
                cp -a "$f" "$WORK/lib/firmware/"
                matched=$((matched + 1))
            done
            shopt -u nullglob
            if [ "$matched" -gt 0 ]; then
                log "  + ${prefix}* ($matched)"
            else
                log "  - ${prefix}* (none)"
            fi
        }
        log "network firmware"
        for p in "${NET_FIRMWARE_PREFIXES[@]}"; do copy_firmware_prefix "$p"; done
        log "  firmware: $(du -sh "$WORK/lib/firmware" | cut -f1)"
    fi
    rm -rf "$TMP_FW"
else
    log "WARN: no $FIRMWARE_PKG_GLOB in $AMOS_PRODUCTION"
fi

if command -v depmod >/dev/null; then
    log "computing module dependencies"
    if ! depmod -a -e -b "$WORK" "$KVER" 2>"$WORK/.depmod.err"; then
        log "  WARN: depmod reported issues:"
        sed 's/^/      /' "$WORK/.depmod.err" | head -20
    fi
    rm -f "$WORK/.depmod.err"
fi
rm -rf "$TMP_K"


issue() {
  cat > "$WORK/etc/issue" <<EOF

================================================================================
  AM·OS ${ISO_PROFILE^} Edition
  Copyright (c) 2026 ANNE Media. All rights reserved.

  Redistribution and use of this software, with or without modification, is
  permitted provided that the following conditions are met:

  1. Redistributions of this software must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  
  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  Unauthorized access to this system is strictly prohibited.
================================================================================

EOF
  chmod 644 "$WORK/etc/issue"
  log "issue: Pre-login banner written"
}

issuemotd() {
  mv $WORK/etc/motd.$ISO_PROFILE $WORK/etc/motd
  chmod 644 "$WORK/etc/motd"
  rm -f $WORK/etc/motd.*
  issue
}

# ============================================================
# initrd-src overlay
# ============================================================
if [ -d "$INITRD_SRC/etc" ]; then
    log "overlaying initrd-src/etc/"
    cp -a "$INITRD_SRC/etc/." "$WORK/etc/"
fi
if [ -d "$INITRD_SRC/files" ]; then
    log "overlaying initrd-src/files/"
    cp -a "$INITRD_SRC/files/." "$WORK/"
fi
issuemotd
# ---- GPG fingerprint ----
[ -f "$GPG_PUBKEY" ] || die "no GPG public key at $GPG_PUBKEY"

GPG_FPR=$(gpg --with-colons --import-options show-only --import \
    "$GPG_PUBKEY" 2>/dev/null \
    | awk -F: '/^fpr:/ {print $10; exit}')
[ -n "$GPG_FPR" ] || die "cannot compute GPG fingerprint from $GPG_PUBKEY"
log "  GPG fingerprint pinned: $GPG_FPR"

cp -a "$GPG_PUBKEY" "$WORK/etc/AMOS-GPG-KEY"
chmod 644 "$WORK/etc/AMOS-GPG-KEY"
log "  GPG public key -> /etc/AMOS-GPG-KEY"

if [ -f "$WORK/etc/amos-prompt.sh" ]; then
    sed -i "s|@GPG_FPR@|$GPG_FPR|" "$WORK/etc/amos-prompt.sh"
else
    die "initrd-src/etc/amos-prompt.sh did not land at /etc/amos-prompt.sh"
fi

# ---- pin critical file modes ----
chmod 755 "$WORK/init"
chmod 755 "$WORK/etc/amos-prompt.sh"
chmod 755 "$WORK/usr/local/bin/setup"
chmod 755 "$WORK/usr/local/bin/chroot-target"
chmod 644 "$WORK/etc/profile.d/amos-banner.sh"
chmod 644 "$WORK/etc/passwd" "$WORK/etc/group"
chmod 640 "$WORK/etc/shadow"

# ============================================================
# pack
# ============================================================
log "packing"
(
    cd "$WORK"
    find . -print0 \
        | sort -z \
        | cpio --null -o -H newc --quiet --owner=root:root \
        | xz -9e --check=crc32 > "$OUT_INITRD"
)
log "wrote: $OUT_INITRD ($(du -h "$OUT_INITRD" | cut -f1))"