#!/bin/bash
set -eu
export LANG=C.utf8
export LC_ALL=C.utf8
export NCURSES_NO_UTF8_ACS=1

PKG_BLACKLIST=(
  busybox
  dropbear
)

IMA_APPRAISE="${IMA_APPRAISE:-log}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=common.sh
. "$SCRIPT_DIR/common.sh"

CONFIG_FILE="${CONFIG_FILE:-/root/amos-install.conf}"

[ -f "$CONFIG_FILE" ] || { echo "ERROR: config not found. Run setup.sh first." >&2; exit 1; }
# shellcheck disable=SC1090
. "$CONFIG_FILE"
ISO_PROFILE=$(<"$ISO_SRC/type") 
if [[ "$ISO_PROFILE" = "edge" ]]; then
 IMA_APPRAISE=enforce
fi
# Default env-only secrets to empty so `set -u` is happy.
ROOT_PASSWORD="${ROOT_PASSWORD:-}"
USER_PASSWORD="${USER_PASSWORD:-}"
LUKS_PASSPHRASE="${LUKS_PASSPHRASE:-}"

# Defaults for variables introduced by newer setup.sh versions, so an
# old config file remains compatible.
ENCRYPT_INTEGRITY="${ENCRYPT_INTEGRITY:-no}"
LVM_ROOT_PERCENT="${LVM_ROOT_PERCENT:-90}"
LVM_DATA_ENABLE="${LVM_DATA_ENABLE:-no}"
LVM_DATA_SIZE_MIB="${LVM_DATA_SIZE_MIB:-0}"
LVM_DATA_NAME="${LVM_DATA_NAME:-data}"
LVM_DATA_MOUNT="${LVM_DATA_MOUNT:-}"

TARGET_ROOT="/target"
MARIADBD_PID=""
VERIFY_GNUPG=""
ROOT_PART=""
BOOT_PART=""
ESP_PART=""
LUKS_PART=""
MYSQL_ROOT_PW=""
ANNODE_CONF_FILE=""
ANNODE_PW_STORED=""
START_TIME=$SECONDS

INSTALL_LOG="/tmp/installpkg.log"
INSTALL_LOG_TARGET="/var/log/installpkg.log"
# LVM warns when it inherits an open file descriptor it does not
# recognise. open_tty() in common.sh holds FD 9 on /dev/tty for
# dialog, so every LVM invocation prints "File descriptor 9
# (/dev/tty) leaked". The FD is benign; suppress the warning at
# the source rather than filtering stderr.
export LVM_SUPPRESS_FD_WARNINGS=1


die() {
  local msg="$*"
  local caller_line="${BASH_LINENO[0]}"
  log "FATAL $msg  (called from line $caller_line)"
  on_error "$caller_line" 1 "$msg"
}

on_error() {
  local line="$1" code="${2:-1}" msg="${3:-}"
  
  # Write directly to the log file first, bypassing the log() function
  printf '[%s] !!!! ABORTED at line %s (exit %s) msg=%s\n' \
    "$(date '+%H:%M:%S')" "$line" "$code" "$msg" >> "$LIVE_LOG"
  
  sync_log_to_target 2>/dev/null || true

  local body
  if [ -n "$msg" ]; then
    body="The installer encountered an error.

  $msg

  Location:  line $line, exit code $code
  Live log:  $LIVE_LOG"
  else
    body="The installer encountered an error.

  Location:  line $line, exit code $code
  Live log:  $LIVE_LOG"
  fi

  if [ -n "$DIALOG_TTY" ]; then
    # Use timeout so a broken dialog doesn't hang the trap
    timeout 10 dialog --cr-wrap --no-collapse \
           --title "Installation failed" --msgbox "$body" 22 80 \
           < /dev/tty > /dev/tty 2>/dev/null || true
  fi
  echo "Installer failed at line $line (exit $code). See $LIVE_LOG." >&2
  exit 1
}


on_exit() {
  sync_log_to_target
  cleanup 2>/dev/null || true
  close_tty
}

trap 'on_error "$LINENO" "$?"' ERR
trap 'on_exit' EXIT

cleanup() {
  if [ -n "$MARIADBD_PID" ] && kill -0 "$MARIADBD_PID" 2>/dev/null; then
    kill "$MARIADBD_PID" 2>/dev/null || true
    sleep 1
    kill -9 "$MARIADBD_PID" 2>/dev/null || true
  fi
  [ -n "${VERIFY_GNUPG:-}" ] && [ -d "$VERIFY_GNUPG" ] && rm -rf "$VERIFY_GNUPG"


  if mountpoint -q "$TARGET_ROOT" 2>/dev/null; then
    swapoff "$TARGET_ROOT/.amos_swap" 2>/dev/null || true
    rm -f "$TARGET_ROOT/.amos_swap"
    local m
    for m in "$TARGET_ROOT/mnt/iso" "$TARGET_ROOT/dev/pts" "$TARGET_ROOT/dev" \
             "$TARGET_ROOT/proc" "$TARGET_ROOT/sys" \
             "$TARGET_ROOT/boot/efi" "$TARGET_ROOT/boot" "$TARGET_ROOT"; do
      mountpoint -q "$m" 2>/dev/null && umount "$m" 2>/dev/null || true
    done
  fi
}

sync_log_to_target() {
  [ -d "$TARGET_ROOT" ] || return 0
  mountpoint -q "$TARGET_ROOT" 2>/dev/null || return 0
  mkdir -p "$TARGET_ROOT$(dirname "$TARGET_LOG_REL")" 2>/dev/null || return 0
  cp -f "$LIVE_LOG" "$TARGET_ROOT$TARGET_LOG_REL" 2>/dev/null || true
  cp -f "$INSTALL_LOG" "$TARGET_ROOT$INSTALL_LOG_TARGET" 2>/dev/null || true
}

require_secrets() {
  local missing=0
  if [ -z "$ROOT_PASSWORD" ]; then
    dlg_msg "Password required" \
"\n  The root password was not supplied by setup.sh.

  You will be asked for it now."
    prompt_root_password || die "Root password entry cancelled."
    missing=1
  fi
  if [ "$ENCRYPT" = "yes" ] && [ "${MANUAL_LAYOUT:-no}" != "yes" ] && [ -z "$LUKS_PASSPHRASE" ]; then
    [ "$missing" = "0" ] && dlg_msg "Passphrase required" \
"\n  The LUKS passphrase was not supplied by setup.sh.

  You will be asked for it now."
    prompt_luks_passphrase || die "Passphrase entry cancelled."
    missing=1
  fi
  if [ -n "$USER_NAME" ] && [ -z "$USER_PASSWORD" ]; then
    [ "$missing" = "0" ] && dlg_msg "Password required" \
"\n  The user password was not supplied by setup.sh.

  You will be asked for it now."
    prompt_user_password || die "User password entry cancelled."
  fi
}

preflight() {
  local cmd
  for cmd in parted mkfs.ext4 chroot installpkg dialog gpg \
             find awk sed grep mount umount mountpoint \
             blkid blockdev mkswap fallocate lsblk \
             cryptsetup lvm wipefs openssl; do
    command -v "$cmd" >/dev/null 2>&1 || die "Required tool missing: $cmd"
  done
  if [ "$BOOTMODE" = "efi" ]; then
    command -v mkfs.vfat >/dev/null 2>&1 \
      || command -v mkfs.fat >/dev/null 2>&1 \
      || die "mkfs.vfat (dosfstools) not found."
  fi
  if [ "${MANUAL_LAYOUT:-no}" != "yes" ]; then
    [ -b "$TARGET_DISK" ] || die "Target disk not a block device: $TARGET_DISK"
  fi
  [ -d "$ISO_SRC/$PKGMAIN" ] || die "ISO source has no $PKGMAIN directory."
}

compute_partition_layout() {
 if [ "${MANUAL_LAYOUT:-no}" = "yes" ]; then
    ROOT_PART="$MANUAL_ROOT"
    [ -n "${MANUAL_ESP:-}" ]        && ESP_PART="$MANUAL_ESP"
    [ -n "${MANUAL_CRYPT_PART:-}" ] && LUKS_PART="$MANUAL_CRYPT_PART"
    [ -n "${MANUAL_BOOT:-}" ]       && BOOT_PART="$MANUAL_BOOT"
    [ -n "$LUKS_PART" ] && LUKS_NAME="luks$(basename "$LUKS_PART")"
    return 0
  fi

  local n=0
  if [ "$BOOTMODE" = "efi" ]; then
    n=$((n+1)); ESP_PART=$(part_name "$TARGET_DISK" "$n")
  fi
  # BIOS needs a separate /boot whenever the root filesystem is
  # behind device-mapper. LILO reads the kernel via BIOS int 13h,
  # which cannot see through LUKS or LVM. Putting /boot on its own
  # plain partition is what makes LILO able to find the kernel.
  if [ "$BOOTMODE" = "bios" ] && \
     { [ "$ENCRYPT" = "yes" ] || [ "$USE_LVM" = "yes" ]; }; then
    n=$((n+1)); BOOT_PART=$(part_name "$TARGET_DISK" "$n")
  fi
  n=$((n+1)); ROOT_PART=$(part_name "$TARGET_DISK" "$n")
  if [ "$ENCRYPT" = "yes" ]; then
    LUKS_PART="$ROOT_PART"
    # Derive the mapper name now, in the parent shell. If we set it
    # inside exec_format (which runs its body in a subshell piped to
    # dialog --gauge), the assignment would be lost when the subshell
    # exits, and exec_mount would look for the wrong path.
    #
    # mkinitrd's boot init derives the mapper name as
    # luks<basename of underlying device>. Matching that name here
    # keeps crypttab, the boot args, and the boot init in agreement.
    LUKS_NAME="luks$(basename "$LUKS_PART")"
  fi
  return 0
}

exec_partition() {
  local rc

  # --- SAFETY CHECK ---
  if grep -qE "^$TARGET_DISK|^$TARGET_DISK[0-9]+" /proc/mounts || losetup -a | grep -q "$TARGET_DISK"; then
    die "FATAL: Target disk $TARGET_DISK is currently busy (likely the live boot disk).

You cannot install to the disk you are currently booted from. 
Since you wrote the ISO directly to $TARGET_DISK and booted it, 
the system is holding it open.

To fix this:
  1. Reboot back into the hosting provider's rescue system.
  2. Use the QEMU method to install, OR use the provider's 'Custom ISO' 
     feature to attach the ISO as a virtual CD-ROM (so it appears as /dev/sr0 or /dev/sr1).
  3. Then run the installer targeting $TARGET_DISK."
  fi
  # --- END SAFETY CHECK ---

    # --- TARGETED CLEANUP (Only runs if Safety Check passes) ---
      if command -v pvs >/dev/null 2>&1; then
        for vg in $(pvs --noheadings -o vg_name "$TARGET_DISK" 2>/dev/null | tr -d ' '); do
          [ -n "$vg" ] && vgchange -an "$vg" >/dev/null 2>&1 || true
        done
      fi

      for part in $(lsblk -pnro NAME "$TARGET_DISK" | grep -v "^$TARGET_DISK$"); do
        if grep -q "^$part " /proc/swaps 2>/dev/null; then
          swapoff "$part" >/dev/null 2>&1 || true
        fi
        mountpoint -q "$part" && umount -l "$part" >/dev/null 2>&1 || true
      done

      # Close any active LUKS containers on the target disk
      # We close the top-level device first, which automatically tears down the _dif layer
      for dm in $(lsblk -pnro NAME,TYPE "$TARGET_DISK" | awk '$2=="crypt"{print $1}' | sort -r); do
        log "Closing active LUKS device: $dm"
        cryptsetup close "$dm" >/dev/null 2>&1 || log "Warning: could not close $dm"
      done
      # --- END TARGETED CLEANUP ---

  (
    echo 5
    echo "XXX"; echo "Writing partition table..."; echo "XXX"

    # If wipefs fails, set -e will abort the subshell.
    # No wipe no dice.
    wipefs -a "$TARGET_DISK" >/dev/null 2>>"$LIVE_LOG" || \
      wipefs -a -f "$TARGET_DISK" >/dev/null 2>>"$LIVE_LOG"

    # parted -s writes alignment warnings and informational chatter to
    # stdout, which would corrupt the dialog --gauge stream. Silence
    # stdout, capture stderr in the log, and let a non-zero exit
    # propagate: under set -e it aborts the subshell, the pipe closes,
    # dlg_gauge exits, and PIPESTATUS[0] below picks up the failure.
    if [ "$BOOTMODE" = "efi" ]; then
      parted -s "$TARGET_DISK" mklabel gpt                    >/dev/null 2>>"$LIVE_LOG"
      parted -s "$TARGET_DISK" mkpart ESP fat32 1MiB \
             "$((1 + ESP_SIZE_MIB))MiB"                       >/dev/null 2>>"$LIVE_LOG"
      parted -s "$TARGET_DISK" set 1 esp on                   >/dev/null 2>>"$LIVE_LOG"
      local start=$((1 + ESP_SIZE_MIB))
      parted -s "$TARGET_DISK" mkpart primary ext4 \
             "${start}MiB" 100%                               >/dev/null 2>>"$LIVE_LOG"
    else
      parted -s "$TARGET_DISK" mklabel msdos                  >/dev/null 2>>"$LIVE_LOG"
      if [ "$ENCRYPT" = "yes" ] || [ "$USE_LVM" = "yes" ]; then
        # sda1 = plain /boot (LILO-readable), sda2 = LUKS and/or LVM
        parted -s "$TARGET_DISK" mkpart primary ext4 1MiB \
               "$((1 + BOOT_SIZE_MIB))MiB"                    >/dev/null 2>>"$LIVE_LOG"
        parted -s "$TARGET_DISK" set 1 boot on                >/dev/null 2>>"$LIVE_LOG"
        parted -s "$TARGET_DISK" mkpart primary ext4 \
               "$((1 + BOOT_SIZE_MIB))MiB" 100%               >/dev/null 2>>"$LIVE_LOG"
      else
        # Single partition: plain root, no device-mapper layer
        parted -s "$TARGET_DISK" mkpart primary ext4 1MiB 100% >/dev/null 2>>"$LIVE_LOG"
        parted -s "$TARGET_DISK" set 1 boot on                >/dev/null 2>>"$LIVE_LOG"
      fi
    fi

    # partprobe asks the kernel to re-read the partition table. It can
    # fail benignly: the kernel may have already picked up the change,
    # or the device may be momentarily busy. Log the failure and show a
    # short note in the dialog message area, but continue — the
    # partition-wait loop below is the authoritative check for whether
    # the partitions actually appeared.
    if ! partprobe "$TARGET_DISK" >/dev/null 2>>"$LIVE_LOG"; then
      echo 10
      echo "XXX"; echo "Note: partprobe failed; kernel auto-detection should still pick up the change"; echo "XXX"
      log "partition: partprobe failed for $TARGET_DISK"
    fi

    # udevadm settle waits for pending udev events. Rarely fails; a
    # failure here is worth knowing about before the wait loop starts.
    if ! udevadm settle >/dev/null 2>>"$LIVE_LOG"; then
      echo 10
      echo "XXX"; echo "Note: udevadm settle timed out; continuing anyway"; echo "XXX"
      log "partition: udevadm settle failed"
    fi

    echo 20
    echo "XXX"; echo "Waiting for partitions..."; echo "XXX"
    local i all_ready
    for i in $(seq 1 15); do
      all_ready=1
      [ -n "$ESP_PART" ]  && [ ! -b "$ESP_PART" ]  && all_ready=0
      [ -n "$BOOT_PART" ] && [ ! -b "$BOOT_PART" ] && all_ready=0
      [ -n "$ROOT_PART" ] && [ ! -b "$ROOT_PART" ] && all_ready=0
      [ "$all_ready" = "1" ] && break
      sleep 1
    done
    [ -z "$ESP_PART" ]  || [ -b "$ESP_PART" ]  || exit 1
    [ -z "$BOOT_PART" ] || [ -b "$BOOT_PART" ] || exit 1
    [ -b "$ROOT_PART" ] || exit 1
    echo 100
  ) | dlg_gauge "Partitioning $TARGET_DISK" "$BOOTMODE layout" 8 72
  rc=${PIPESTATUS[0]}
  [ "$rc" -eq 0 ] || die "Partitioning failed (exit $rc)"
  log "Partitioning complete."
}

format_fs() {
  local dev="$1" label="$2"
  case "$FSTYPE" in
    ext4)  mkfs.ext4 -F -O 64bit,metadata_csum -L "$label" "$dev" 2>>"$LIVE_LOG" ;;
    xfs)   mkfs.xfs -f -L "$label" "$dev" 2>>"$LIVE_LOG";;
    btrfs) mkfs.btrfs -f -L "$label" "$dev" 2>>"$LIVE_LOG" 2>&1 ;;
    *)     die "Unsupported filesystem: $FSTYPE" ;;
  esac
}

exec_format() {
  local luks_dev="$ROOT_PART"
  local rc
   # The installer initrd does not load dm-integrity by default, and
  # cryptsetup's autoload via libdevmapper is unreliable in the initrd
  # environment: the kernel rejects the integrity target with EINVAL
  # before the module has finished loading, and cryptsetup reports
  # "Cannot format integrity". Load it explicitly here.
  if [ "$ENCRYPT" = "yes" ] && [ "$ENCRYPT_INTEGRITY" = "yes" ]; then
    modprobe dm-integrity 2>>"$LIVE_LOG" \
      || die "cannot load dm-integrity module (required for authenticated encryption)"
    log "dm-integrity module loaded"
  fi
  (
    echo 10
    if [ -n "$ESP_PART" ]; then
      echo "XXX"; echo "Formatting EFI system partition..."; echo "XXX"
      mkfs_vfat -F32 -n EFI "$ESP_PART" >/dev/null 2>&1
    fi
    if [ -n "$BOOT_PART" ]; then
      echo 30
      echo "XXX"; echo "Formatting /boot..."; echo "XXX"
      mkfs.ext4 -F -O 64bit,metadata_csum -L amosboot "$BOOT_PART" >/dev/null 2>&1
    fi
    if [ "$ENCRYPT" = "yes" ]; then
      echo 50
      if [ "$ENCRYPT_INTEGRITY" = "yes" ]; then
        echo "XXX"; echo "Creating encrypted container (AES-XTS + HMAC-SHA256)..."; echo "XXX"
        # dm-integrity journal mode only supports 512-byte sectors.
        # Passing --sector-size 4096 here makes the kernel reject the
        # dm-crypt table with EINVAL, cryptsetup reports "Cannot
        # format integrity", and the install aborts. Do not add
        # --sector-size to this branch.
        printf '%s' "$LUKS_PASSPHRASE" | \
          cryptsetup luksFormat --type luks2 --batch-mode \
            --cipher aes-xts-plain64 \
            --integrity hmac-sha256 \
            --key-file - "$luks_dev" >/dev/null 2>>"$LIVE_LOG"
      else
        echo "XXX"; echo "Creating encrypted container (AES-XTS)..."; echo "XXX"
        # LUKS2 with cryptsetup's default cipher, aes-xts-plain64,
        # key derived from the passphrase via Argon2id. AES-XTS is
        # accelerated by AES-NI on every modern x86 CPU, and the
        # kernel AES modules (aes-x86_64, aesni-intel) pass the
        # hardening audit and are not blacklisted. Sector size 4096
        # matches typical SSD physical sectors.
        printf '%s' "$LUKS_PASSPHRASE" | \
          cryptsetup luksFormat --type luks2 --batch-mode \
            --sector-size 4096 \
            --key-file - "$luks_dev" >/dev/null 2>>"$LIVE_LOG"
      fi
      printf '%s' "$LUKS_PASSPHRASE" | \
        cryptsetup open --key-file - "$luks_dev" "$LUKS_NAME" >/dev/null 2>>"$LIVE_LOG"
      [ -e "/dev/mapper/$LUKS_NAME" ] || exit 1
      luks_dev="/dev/mapper/$LUKS_NAME"
    fi
    if [ "$USE_LVM" = "yes" ]; then
      echo 65
      echo "XXX"; echo "Setting up LVM..."; echo "XXX"
      pvcreate -ff -y "$luks_dev" >/dev/null 2>>"$LIVE_LOG"
      vgcreate "$VG_NAME" "$luks_dev" >/dev/null 2>>"$LIVE_LOG"

      if [ "$LVM_DATA_ENABLE" = "yes" ] && [ -n "$LVM_DATA_MOUNT" ]; then
        local vg_size_mib reserve_mib root_size_mib
        vg_size_mib=$(vgs --noheadings --units m --nosuffix -o vg_size "$VG_NAME" 2>/dev/null | tr -d ' ')
        vg_size_mib="${vg_size_mib%.*}"
        [ -n "$vg_size_mib" ] || { echo "XXX"; echo "cannot read VG size"; echo "XXX"; exit 1; }

        reserve_mib=$(( vg_size_mib * 10 / 100 ))
        root_size_mib=$(( vg_size_mib - reserve_mib - LVM_DATA_SIZE_MIB ))

        if [ "$root_size_mib" -lt 1024 ]; then
          echo "XXX"; echo "root LV would be under 1 GiB; refusing"; echo "XXX"
          exit 1
        fi

        lvm lvcreate -y -L "${root_size_mib}M" \
          -n "$LV_NAME" "$VG_NAME" >/dev/null 2>>"$LIVE_LOG"
        lvm lvcreate -y -L "${LVM_DATA_SIZE_MIB}M" \
          -n "$LVM_DATA_NAME" "$VG_NAME" >/dev/null 2>>"$LIVE_LOG"
        if ! lvm vgmknodes >/dev/null 2>>"$LIVE_LOG"; then
          log "LVM: vgmknodes failed (device nodes may already exist via udev)"
        fi

        log "LVM: vg=${vg_size_mib}M root=${root_size_mib}M data=${LVM_DATA_SIZE_MIB}M reserve=${reserve_mib}M"
      else
        lvm lvcreate -y -l "${LVM_ROOT_PERCENT}%FREE" \
          -n "$LV_NAME" "$VG_NAME" >/dev/null 2>>"$LIVE_LOG"
        if ! lvm vgmknodes >/dev/null 2>>"$LIVE_LOG"; then
          log "LVM: vgmknodes failed (device nodes may already exist via udev)"
        fi
      fi

      luks_dev="/dev/$VG_NAME/$LV_NAME"
      [ -e "$luks_dev" ] || exit 1
    fi
    echo 80
    echo "XXX"; echo "Creating $FSTYPE filesystem..."; echo "XXX"
    format_fs "$luks_dev" amosroot
    if [ "$USE_LVM" = "yes" ] && [ "$LVM_DATA_ENABLE" = "yes" ] && [ -n "$LVM_DATA_MOUNT" ]; then
      format_fs "/dev/$VG_NAME/$LVM_DATA_NAME" amosdata
    fi
    echo 100
  ) | dlg_gauge "Creating filesystems" "Preparing..." 8 72
  rc=${PIPESTATUS[0]}
  [ "$rc" -eq 0 ] || die "Filesystem creation failed (exit $rc)"
  log "Formatting complete."
}

exec_mount() {
  local root_dev data_dev
  if [ "${MANUAL_LAYOUT:-no}" = "yes" ]; then
    root_dev="$MANUAL_ROOT"
  elif [ "$USE_LVM" = "yes" ]; then
    root_dev="/dev/$VG_NAME/$LV_NAME"
  elif [ "$ENCRYPT" = "yes" ]; then
    root_dev="/dev/mapper/$LUKS_NAME"
  else
    root_dev="$ROOT_PART"
  fi
  mkdir -p "$TARGET_ROOT"
  if [ ! -e "$root_dev" ]; then
    log "FATAL: root device $root_dev does not exist at mount time"
    die "Root device $root_dev does not exist"
  fi
  mount "$root_dev" "$TARGET_ROOT" 2>>"$LIVE_LOG"
  # The root inode of the freshly formatted filesystem comes out as
  # mode 0750. Non-root processes that chroot into this filesystem --
  # mariadbd running as uid 27 -- need the x bit on the chroot root
  # itself before they can attempt to exec anything inside. Root
  # bypasses this via CAP_DAC_READ_SEARCH, which is why uid 0 works
  # and uid 27 fails on identical files.
  chmod 755 "$TARGET_ROOT"

  [ -n "$BOOT_PART" ] && { mkdir -p "$TARGET_ROOT/boot"; mount "$BOOT_PART" "$TARGET_ROOT/boot"; }
  [ -n "$ESP_PART" ]  && { mkdir -p "$TARGET_ROOT/boot/efi"; mount "$ESP_PART" "$TARGET_ROOT/boot/efi"; }
  mkdir -p "$TARGET_ROOT/proc" "$TARGET_ROOT/sys" "$TARGET_ROOT/dev" "$TARGET_ROOT/mnt/iso"
  mount --bind /dev  "$TARGET_ROOT/dev"
  mount --bind /proc "$TARGET_ROOT/proc"
  mount --bind /sys  "$TARGET_ROOT/sys"
  mount --bind "$ISO_SRC" "$TARGET_ROOT/mnt/iso"
  # Mount the data LV (if any) before packages install, so anything
  # the packages write to $LVM_DATA_MOUNT lands on the data volume
  # from the start rather than being created on root and needing a
  # copy later.
  if [ "$USE_LVM" = "yes" ] && [ "$LVM_DATA_ENABLE" = "yes" ] && [ -n "$LVM_DATA_MOUNT" ]; then
    local data_dev="/dev/$VG_NAME/$LVM_DATA_NAME"
    [ -e "$data_dev" ] || die "Data LV $data_dev does not exist at mount time"
    mkdir -p "$TARGET_ROOT$LVM_DATA_MOUNT"
    chmod 755 "$TARGET_ROOT$LVM_DATA_MOUNT"
    mount "$data_dev" "$TARGET_ROOT$LVM_DATA_MOUNT" 2>>"$LIVE_LOG"
    log "Data LV mounted at $LVM_DATA_MOUNT"
  fi
  log "Target mounted at $TARGET_ROOT from $root_dev"
  sync_log_to_target
}

verify_signed_manifest() {
  local manifest="$1" signature="$2" keyfile="$3" workdir="$4" hashtool="$5"
  local gnupg out

  log "verify: manifest=$manifest"
  [ -f "$manifest" ]  || { log "verify: FAILED - manifest missing"; return 1; }
  [ -f "$signature" ] || { log "verify: FAILED - signature missing"; return 1; }
  [ -f "$keyfile" ]   || { log "verify: FAILED - keyfile missing"; return 1; }
  [ -d "$workdir" ]   || { log "verify: FAILED - workdir missing"; return 1; }

  gnupg=$(mktemp -d); chmod 700 "$gnupg"

  if ! out=$(GNUPGHOME="$gnupg" gpg --quiet --import "$keyfile" 2>&1); then
    log "verify: FAILED - gpg --import"
    printf '%s\n' "$out" | sed 's/^/  gpg: /' >> "$LIVE_LOG"
    rm -rf "$gnupg"; return 1
  fi
  log "verify: import ok"

  if ! out=$(GNUPGHOME="$gnupg" gpg --quiet --verify \
             "$signature" "$manifest" 2>&1); then
    log "verify: FAILED - gpg --verify"
    printf '%s\n' "$out" | sed 's/^/  gpg: /' >> "$LIVE_LOG"
    rm -rf "$gnupg"; return 1
  fi
  log "verify: signature ok"
  rm -rf "$gnupg"

  if ! out=$( cd "$workdir" && "$hashtool" -c --quiet "$(basename "$manifest")" 2>&1 ); then
    log "verify: FAILED - checksum mismatch"
    printf '%s\n' "$out" | head -20 | sed 's/^/  hash: /' >> "$LIVE_LOG"
    return 1
  fi
  log "verify: checksums ok"
  return 0
}

exec_verify_packages() {
  if [ "${SKIP_VERIFY:-0}" = "1" ]; then
    warn "SKIP_VERIFY=1: package verification skipped"
    return 0
  fi

  if [ -f "$ISO_SRC/$PKGMAIN/CHECKSUMS.md5" ]    && \
     [ -f "$ISO_SRC/$PKGMAIN/CHECKSUMS.md5.asc" ] && \
     [ -f "$ISO_SRC/AMOS-GPG-KEY" ]; then

    log "Verifying package tree..."

    if ! verify_signed_manifest \
        "$ISO_SRC/$PKGMAIN/CHECKSUMS.md5" \
        "$ISO_SRC/$PKGMAIN/CHECKSUMS.md5.asc" \
        "$ISO_SRC/AMOS-GPG-KEY" \
        "$ISO_SRC/$PKGMAIN" \
        md5sum; then

      local detail
      detail=$(grep 'verify:' "$LIVE_LOG" | tail -12 | sed 's/^\[[0-9:]*\] //')

      die "Package verification failed.

$detail

The installation media may be corrupt or tampered with."
    fi
    log "Package verification passed."
  else
    warn "Verification artifacts missing on ISO; skipping."
  fi
}

add_temp_swap() {
  # Create a temporary 4GB swap file on the target disk to prevent OOM
  # while extracting large packages like kernel-firmware.
  fallocate -l 4G "$TARGET_ROOT/.amos_swap" 2>/dev/null || \
    dd if=/dev/zero of="$TARGET_ROOT/.amos_swap" bs=1M count=4096 status=none
  chmod 600 "$TARGET_ROOT/.amos_swap"
  mkswap "$TARGET_ROOT/.amos_swap" >/dev/null
  swapon "$TARGET_ROOT/.amos_swap" || log "WARN: Could not swapon target swap"

}
exec_install_packages() {
  log "The current edition is: $ISO_PROFILE"
  mkdir -p "$TARGET_ROOT/etc/amos"
  echo "$ISO_PROFILE" > "$TARGET_ROOT/etc/amos/edition"

  local series_list=(a ap d l n x y k z)
  local -a all_pkgs=()
  local series pkgdir pkg base bl skip
  local blacklisted=0
  for series in "${series_list[@]}"; do
    if [ "$series" = "extra" ]; then pkgdir="$ISO_SRC/extra"; else pkgdir="$ISO_SRC/$PKGMAIN/$series"; fi
    [ -d "$pkgdir" ] || continue
    for pkg in "$pkgdir"/*.t?z; do
      [ -f "$pkg" ] || continue
      base=$(basename "$pkg")
      skip=0
      for bl in "${PKG_BLACKLIST[@]}"; do
        case "$base" in
          "${bl}-"*) skip=1; break ;;
        esac
      done
      if [ "$skip" = "1" ]; then
        blacklisted=$((blacklisted + 1))
        log "Blacklisted: $base"
        continue
      fi
      all_pkgs+=("$pkg")
    done
  done
  local total=${#all_pkgs[@]}
  [ "$total" -gt 0 ] || die "No packages found on installation media."
  [ "$blacklisted" -gt 0 ] && log "Blacklisted $blacklisted package(s) on the ISO."


  local fail_log
  fail_log=$(mktemp)
  : > "$INSTALL_LOG"

  (
    umask 022
    local i=0
    for pkg in "${all_pkgs[@]}"; do
      # 1. Calculate and update the UI FIRST
      i=$((i+1))
      echo $((i * 100 / total))
      echo "XXX"
      echo "Installing $(basename "$pkg")..."
      echo "XXX"
      # 2. Then do the heavy lifting (which will block the UI temporarily)
      installpkg --root "$TARGET_ROOT" --terse "$pkg" >> "$INSTALL_LOG" 2>&1 \
        || echo "$pkg" >> "$fail_log"
    done
    echo 100
  ) | dlg_gauge "Installing AM·OS ($total packages)" "Starting..." 8 72

  local failed
  failed=$(wc -l < "$fail_log")
  
  if [ "$failed" -gt 0 ]; then
    log "Failed packages:"
    cat "$fail_log" | while read -r p; do log "  $p"; done
    log "Last 15 lines of installpkg log:"
    tail -n 15 "$INSTALL_LOG" | sed 's/^/    /' >> "$LIVE_LOG"
    rm -f "$fail_log"
    die "Package installation failed for $failed package(s). See $LIVE_LOG and /tmp/installpkg.log."
  fi
  
  rm -f "$fail_log"
  log "Installed $total packages."
}

# ---------------------------------------------------------------------------
# exec_sysctl_hardening
#
# Write a sysctl drop-in with the Kernel Self Protection Project's
# recommended values. Applied at boot by rc.sysctl.
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# exec_sysctl_hardening
#
# Write a sysctl drop-in with the hardening profile for a strict webhosting
# node. Three tiers:
#
#   Tier A: maximum value, no operational cost for this workload.
#   Tier B: maximum value with a documented tradeoff; each entry is
#           accompanied by a comment explaining the cost.
#   Tier C: deliberately absent. log_martians floods the kernel log on
#           a public interface; panic_on_oops turns a single oops into
#           a reboot; icmp_echo_ignore_all breaks monitoring; modules_
#           disabled is a boot parameter, not a sysctl.
#
# Applied at boot by `sysctl --system`, which reads /etc/sysctl.conf
# followed by /etc/sysctl.d/*.conf in lexical order.
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# exec_sysctl_hardening
#
# Write a sysctl drop-in with the hardening profile for a strict webhosting
# node. Three tiers:
#
#   Tier A: maximum value, no operational cost for this workload.
#   Tier B: maximum value with a documented tradeoff; each entry is
#           accompanied by a comment explaining the cost.
#   Tier C: deliberately absent. log_martians floods the kernel log on
#           a public interface; panic_on_oops turns a single oops into
#           a reboot; icmp_echo_ignore_all breaks monitoring; modules_
#           disabled is a boot parameter, not a sysctl.
#
# Applied at boot by `sysctl --system`, which reads /etc/sysctl.conf
# followed by /etc/sysctl.d/*.conf in lexical order.
# ---------------------------------------------------------------------------
exec_sysctl_hardening() {
  local dir="$TARGET_ROOT/etc/sysctl.d"
  mkdir -p "$dir"

  cat > "$dir/99-amos-hardening.conf" <<'EOF'
# AM·OS: sysctl hardening for a strict webhosting node.
#
# Sources: Kernel Self Protection Project recommended settings,
# Debian hardening-runtime 10-hardening.conf, Kicksecure security-misc.
# Values that deviate from those references carry a comment explaining
# why.

# --- Tier A: maximum, no cost for this workload ---

# Kernel pointer exposure. 2 hides pointers from everyone, including
# root. Only perf, crash, and some BPF loaders need the values; none
# run on this node.
kernel.kptr_restrict = 2

# Kernel ring buffer. Readable only with CAP_SYSLOG.
kernel.dmesg_restrict = 1

# Perf events. 3 blocks unprivileged profiling entirely.
# (On kernels without the perf_event_paranoid=3 distro patch this
# behaves as 2. Either is fine for this node.)
kernel.perf_event_paranoid = 3

# kexec. Off anyway in AM·OS kernel; the syscall does not exist, the code is not compiled in, so there is nothing to disable. 
# kernel.kexec_load_disabled = 1

# Unprivileged BPF. 2 means permanently disabled until reboot.
# No BPF tooling on this node.
kernel.unprivileged_bpf_disabled = 2

# BPF JIT hardening, when the JIT is in use.
net.core.bpf_jit_harden = 2

# BPF JIT kallsyms. 1 exposes JIT-compiled BPF addresses through
# /proc/kallsyms. Combined with the pointer hiding above, non-root
# cannot read them but root can, and a BPF JIT address is a
# reliable KASLR bypass once known. 0 removes the exposure entirely.
net.core.bpf_jit_kallsyms = 0

# TTY line discipline autoload. Blocks CVE-2017-2636 class attacks.
dev.tty.ldisc_autoload = 0

# Core dumps from setuid processes are never written.
fs.suid_dumpable = 0

# Symlink / fifo / regular-file race protections.
fs.protected_fifos = 2
fs.protected_regular = 2
fs.protected_symlinks = 1
fs.protected_hardlinks = 1

# ASLR entropy on x86_64. 32 is the maximum.
vm.mmap_rnd_bits = 32

# Network: anti-spoofing, SYN flood protection, ICMP hygiene.
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_rfc1337 = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1

net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.all.router_solicitations = 0
net.ipv6.conf.default.router_solicitations = 0
net.ipv6.conf.all.autoconf = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.all.use_tempaddr = 2
net.ipv6.conf.default.use_tempaddr = 2

# --- Tier B: maximum with a documented tradeoff ---

# Ptrace. 3 disables ptrace entirely, including for root and for
# launching a program under a debugger. This blocks strace, gdb,
# ltrace, and any monitoring agent that attaches to a live process.
# The debugging interfaces this node relies on are logs, /proc, and
# /sys, none of which use ptrace. If interactive debugging is ever
# needed, lower the value at runtime:
#     sysctl -w kernel.yama.ptrace_scope=0
# The change does not require a reboot.
kernel.yama.ptrace_scope = 3

# SysRq. 1 enables sync, remount-ro, and reboot only. 0 disables the
# feature entirely and removes the only clean way to recover a hung
# remote server without a power cycle.
kernel.sysrq = 1

# User namespaces. 0 is the maximum. This node runs no containers;
# no Podman, no Docker, no bwrap. Blocks a large unprivileged attack
# surface.
#
# kernel.unprivileged_userns_clone is the Debian-specific variant of
# the same setting. This kernel does isn't compiled with the Debian patch. 
user.max_user_namespaces is the authoritative control.
user.max_user_namespaces = 0

# --- Tier C: deliberately absent ---
#
# net.ipv4.conf.all.log_martians
#   Floods the kernel log on a public-facing interface. Forensics
#   belong in a packet capture, not in printk.
#
# kernel.panic_on_oops
#   Turns any single oops into a reboot. Wrong failure mode for a
#   server that must stay up while you read the trace.
#
# net.ipv4.icmp_echo_ignore_all
#   Security theatre. Breaks monitoring and uptime checks. Rate-limit
#   in iptables if needed.
#
# kernel.modules_disabled
#   A kernel command-line parameter, not a sysctl. Belongs in the
#   bootloader config if you want it, not here.
EOF

  chmod 644 "$dir/99-amos-hardening.conf"
  log "Sysctl hardening written to /etc/sysctl.d/99-amos-hardening.conf"
}

exec_system_config() {
  local root_hash root_dev root_uuid boot_uuid esp_uuid luks_uuid
  root_hash=$(openssl passwd -6 "$ROOT_PASSWORD")

  if [ "${MANUAL_LAYOUT:-no}" = "yes" ]; then
    root_dev="$MANUAL_ROOT"
  elif [ "$USE_LVM" = "yes" ]; then
    root_dev="/dev/$VG_NAME/$LV_NAME"
  elif [ "$ENCRYPT" = "yes" ]; then
    root_dev="/dev/mapper/$LUKS_NAME"
  else
    root_dev="$ROOT_PART"
  fi
  root_uuid=$(blkid -s UUID -o value "$root_dev" 2>/dev/null || true)

  {
    if [ -n "$root_uuid" ]; then
      printf 'UUID=%s  /  %s  defaults  0  0\n' "$root_uuid" "$FSTYPE"
    else
      printf '%s  /  %s  defaults  0  0\n' "$root_dev" "$FSTYPE"
    fi
    if [ -n "$BOOT_PART" ]; then
      boot_uuid=$(blkid -s UUID -o value "$BOOT_PART")
      printf 'UUID=%s  /boot  ext4  defaults  1  2\n' "$boot_uuid"
    fi
    if [ -n "$ESP_PART" ]; then
      esp_uuid=$(blkid -s UUID -o value "$ESP_PART")
      printf 'UUID=%s  /boot/efi  vfat  umask=0077  0  2\n' "$esp_uuid"
    fi
    if [ "$USE_LVM" = "yes" ] && [ "$LVM_DATA_ENABLE" = "yes" ] && [ -n "$LVM_DATA_MOUNT" ]; then
      local data_uuid
      data_uuid=$(blkid -s UUID -o value "/dev/$VG_NAME/$LVM_DATA_NAME")
      printf 'UUID=%s  %s  %s  defaults  1  2\n' "$data_uuid" "$LVM_DATA_MOUNT" "$FSTYPE"
    fi
  } > "$TARGET_ROOT/etc/fstab"

  # AM·OS hardening: tmpfs mounts do not permit execution.
  # IMA's dont_appraise for tmpfs (fsmagic=0x01021994) relies on this.
  # Without noexec, an attacker could drop an unsigned ELF in /tmp or
  # /dev/shm and execute it without appraisal.
  {
    printf '\n# AM·OS hardening: tmpfs is not executable.\n'
    printf 'tmpfs  /tmp      tmpfs  rw,nosuid,nodev,noexec,size=256M,mode=1777  0 0\n'
    printf 'tmpfs  /var/tmp  tmpfs  rw,nosuid,nodev,noexec,size=256M,mode=1777  0 0\n'
    printf 'tmpfs  /dev/shm  tmpfs  rw,nosuid,nodev,noexec,mode=1777            0 0\n'
  } >> "$TARGET_ROOT/etc/fstab"
  
  if [ "$ENCRYPT" = "yes" ] && [ -n "$LUKS_PART" ]; then
    luks_uuid=$(blkid -s UUID -o value "$LUKS_PART" 2>/dev/null || true)
    if [ -n "$luks_uuid" ]; then
      printf '%s  UUID=%s  none  luks\n' "$LUKS_NAME" "$luks_uuid" \
        > "$TARGET_ROOT/etc/crypttab"
      chmod 600 "$TARGET_ROOT/etc/crypttab"
      log "crypttab: $LUKS_NAME UUID=$luks_uuid"
    else
      warn "cannot read LUKS UUID from $LUKS_PART"
    fi
  fi

  local existing_swap=""
  if [ "${MANUAL_LAYOUT:-no}" = "yes" ] && [ -n "${MANUAL_DISK:-}" ]; then
    local dev dev_parent
    while IFS= read -r dev; do
      [ -b "$dev" ] || continue
      [ "$(blkid -s TYPE -o value "$dev" 2>/dev/null)" = "swap" ] || continue
      dev_parent=$(lsblk -no PKNAME "$dev" 2>/dev/null | head -1)
      [ -n "$dev_parent" ] || continue
      [ "/dev/$dev_parent" = "$MANUAL_DISK" ] || continue
      existing_swap="$dev"
      break
    done < <(lsblk -pnro NAME,TYPE 2>/dev/null | awk '$2=="part"{print $1}')
  fi

  if [ -n "$existing_swap" ]; then
    local sw_uuid
    sw_uuid=$(blkid -s UUID -o value "$existing_swap")
    if [ -n "$sw_uuid" ]; then
      printf '\n# Existing swap partition on the root disk.\nUUID=%s  none  swap  sw  0  0\n' \
          "$sw_uuid" >> "$TARGET_ROOT/etc/fstab"
      log "Using existing swap partition $existing_swap"
    fi
  elif [ "$SWAP_SIZE_MIB" -gt 0 ]; then
      [ -e "$TARGET_ROOT/swapfile" ] && rm -f "$TARGET_ROOT/swapfile"

      local swap_ok=0

      if [ "$FSTYPE" = "btrfs" ]; then
          if chroot "$TARGET_ROOT" btrfs filesystem mkswapfile \
              -s "${SWAP_SIZE_MIB}M" /swapfile >>"$LIVE_LOG" 2>&1; then
              swap_ok=1
          else
              warn "btrfs mkswapfile failed; system will boot with zram-only swap"
          fi
      else
          fallocate -l "${SWAP_SIZE_MIB}M" "$TARGET_ROOT/swapfile"
          chmod 600 "$TARGET_ROOT/swapfile"
          chown 0:0  "$TARGET_ROOT/swapfile"
          mkswap "$TARGET_ROOT/swapfile" >/dev/null
          swap_ok=1
      fi

      if [ "$swap_ok" = "1" ]; then
          printf '\n# AM·OS swap file.\n/swapfile  none  swap  sw  0  0\n' >> "$TARGET_ROOT/etc/fstab"
      fi
  fi
  # securityfs is required for AppArmor userspace tools (aa-status,
  # apparmor_parser introspection).
  if ! grep -qE '^[^#].*securityfs' "$TARGET_ROOT/etc/fstab"; then
    printf '\n# securityfs: required by AppArmor userspace tools.\nnone  /sys/kernel/security  securityfs  defaults  0  0\n' \
      >> "$TARGET_ROOT/etc/fstab"
    log "fstab: securityfs entry added"
  fi
  echo "$TARGET_HOSTNAME" > "$TARGET_ROOT/etc/HOSTNAME"
    # /etc/hosts: mariadb-install-db (and other tools) require the
  # hostname to resolve. A minimal hosts file is standard.
  cat > "$TARGET_ROOT/etc/hosts" <<EOF
127.0.0.1   localhost
127.0.1.1   $TARGET_HOSTNAME
::1         localhost ip6-localhost ip6-loopback
EOF

  chmod 644 "$TARGET_ROOT/etc/hosts"
  log "hosts: written ($TARGET_HOSTNAME)"

  if [ "$BOOTMODE" = "efi" ]; then
    if ! grep -qE '^[^#].*efivarfs' "$TARGET_ROOT/etc/fstab"; then
      printf '\n# efivarfs: required by efibootmgr. Mounted read-only to\n# prevent firmware variable writes outside an explicit remount.\nnone  /sys/firmware/efi/efivars  efivarfs  ro  0  0\n' \
        >> "$TARGET_ROOT/etc/fstab"
      log "fstab: efivarfs entry added (EFI boot, ro)"
    fi
  fi

  if [ -n "$KEYMAP" ]; then
      mkdir -p "$TARGET_ROOT/etc/amos"
      printf 'KEYMAP="%s"\n' "$KEYMAP" > "$TARGET_ROOT/etc/amos/keymap.conf"
      chmod 600 "$TARGET_ROOT/etc/amos/keymap.conf"
  fi

    # --- UTF-8 Locale Setup ---
  log "Configuring UTF-8 locale..."
  if [ -x "$TARGET_ROOT/usr/bin/localedef" ]; then
    chroot "$TARGET_ROOT" /usr/bin/localedef -i en_US -f UTF-8 en_US.utf8 >>"$LIVE_LOG" 2>&1 || \
      warn "localedef failed; falling back to C.utf8"
    LOCAL_LANG="en_US.utf8"
  else
    warn "localedef not found in target; falling back to C.utf8"
    LOCAL_LANG="C.utf8"
  fi

  mkdir -p "$TARGET_ROOT/etc/amos"
  cat > "$TARGET_ROOT/etc/amos/locale.conf" <<EOF
LANG="$LOCAL_LANG"
LC_ALL="$LOCAL_LANG"
EOF
  chmod 600 "$TARGET_ROOT/etc/amos/locale.conf"

  echo "LANG=$LOCAL_LANG" > "$TARGET_ROOT/etc/environment"
  echo "LC_ALL=$LOCAL_LANG" >> "$TARGET_ROOT/etc/environment"

  if [ -n "$TIMEZONE" ] && [ -e "$TARGET_ROOT/usr/share/zoneinfo/$TIMEZONE" ]; then
    ln -sf "/usr/share/zoneinfo/$TIMEZONE" "$TARGET_ROOT/etc/localtime"
    echo "$TIMEZONE" > "$TARGET_ROOT/etc/timezone"
  fi

  awk -F: -v h="$root_hash" 'BEGIN{OFS=":"} $1=="root"{$2=h} {print}' \
    "$TARGET_ROOT/etc/shadow" > "$TARGET_ROOT/etc/shadow.tmp"
  mv "$TARGET_ROOT/etc/shadow.tmp" "$TARGET_ROOT/etc/shadow"
  chmod 600 "$TARGET_ROOT/etc/shadow"
  chown 0:0  "$TARGET_ROOT/etc/shadow"

    # login.defs: make the shadow suite's defaults match what the
  # installer writes. openssl passwd -6 produces a SHA512 crypt hash;
  # without this, a later interactive 'passwd' silently downgrades to
  # SHA256 (ENCRYPT_METHOD) and creates new accounts with an
  # unrestricted password lifetime (PASS_MAX_DAYS) and world-readable
  # home directories (no HOME_MODE).
  LD="$TARGET_ROOT/etc/login.defs"
  if [ -f "$LD" ]; then
    _set_ld() {
      local k="$1" v="$2"
      if grep -qE "^[[:space:]]*${k}[[:space:]]" "$LD"; then
        sed -i -E "s|^[[:space:]]*${k}[[:space:]].*|${k}\t${v}|" "$LD"
      else
        printf '%s\t%s\n' "$k" "$v" >> "$LD"
      fi
    }
    _set_ld ENCRYPT_METHOD SHA512
    _set_ld PASS_MAX_DAYS  365
    _set_ld PASS_MIN_DAYS  1
    _set_ld PASS_WARN_AGE  7
    _set_ld UMASK          027
    if ! grep -qE '^[[:space:]]*HOME_MODE[[:space:]]' "$LD"; then
      printf 'HOME_MODE\t0750\n' >> "$LD"
    fi
    unset -f _set_ld
    log "login.defs: policy defaults set"
  fi

  if [ -n "$USER_NAME" ]; then
    chroot "$TARGET_ROOT" /usr/sbin/useradd -m -s /bin/bash "$USER_NAME"
    local uh
    uh=$(openssl passwd -6 "$USER_PASSWORD")
    awk -F: -v u="$USER_NAME" -v h="$uh" 'BEGIN{OFS=":"} $1==u{$2=h} {print}' \
      "$TARGET_ROOT/etc/shadow" > "$TARGET_ROOT/etc/shadow.tmp"
    mv "$TARGET_ROOT/etc/shadow.tmp" "$TARGET_ROOT/etc/shadow"
    chmod 600 "$TARGET_ROOT/etc/shadow"
  fi

  local rc_conf="$TARGET_ROOT/etc/rc.d/rc.inet1.conf"
  if [ -f "$rc_conf" ]; then
    # Safely remove existing settings for interface 0 to prevent conflicts.
    # We only delete the exact lines; we do not overwrite the file.
    sed -i '/^IPADDR\[0\]=/d' "$rc_conf"
    sed -i '/^NETMASK\[0\]=/d' "$rc_conf"
    sed -i '/^USE_DHCP\[0\]=/d' "$rc_conf"
    sed -i '/^DHCP_HOSTNAME\[0\]=/d' "$rc_conf"
    sed -i '/^IFNAME\[0\]=/d' "$rc_conf"
    sed -i '/^GATEWAY=/d' "$rc_conf"

    if [ "$NETWORK_MODE" = "dhcp" ]; then
      # Append DHCP configuration
      cat <<EOF >> "$rc_conf"

# AM·OS installer configuration
IFNAME[0]="$NETWORK_IFACE"
USE_DHCP[0]="yes"
EOF
      log "Network: DHCP on $NETWORK_IFACE"
      
    elif [ "$NETWORK_MODE" = "static" ] && [ -n "$NETWORK_IFACE" ]; then
      local ipaddr="${NETWORK_IP%%/*}"
      local prefix="${NETWORK_IP##*/}"
      local netmask
      netmask=$(awk -v p="$prefix" 'BEGIN{
        n=int(p); m=0
        for (i=0; i<n; i++) m = m*2 + 1
        for (i=n; i<32; i++) m = m*2
        printf "%d.%d.%d.%d", int(m/16777216)%256, int(m/65536)%256, int(m/256)%256, m%256
      }')
      
      # Append Static configuration
      cat <<EOF >> "$rc_conf"

# AM·OS installer configuration
IFNAME[0]="$NETWORK_IFACE"
IPADDR[0]="$ipaddr"
NETMASK[0]="$netmask"
USE_DHCP[0]=""
GATEWAY="$NETWORK_GATEWAY"
EOF
      log "Network: static on $NETWORK_IFACE ($ipaddr/$prefix via $NETWORK_GATEWAY)"
    fi
  fi

  mkdir -p "$TARGET_ROOT/etc"
  cat > "$TARGET_ROOT/etc/netmode.conf" <<EOF
ANNODE_CGROUP="annode"
HOST_SSH_IP="${SSH_ALLOW_FROM}"
SSH_PORT="${SSH_PORT:-62222}"
DEFAULT_TIMEOUT="300"
EOF
  chmod 644 "$TARGET_ROOT/etc/netmode.conf"
  log "netmode.conf written (HOST_SSH_IP=$SSH_ALLOW_FROM, SSH_PORT=${SSH_PORT:-62222})"

  local s f b
  for s in sendmail atd cups alsa ntp elogind cgconfig cgred; do
    f="$TARGET_ROOT/etc/rc.d/rc.$s"
    [ -f "$f" ] || { log "disable $s: not present"; continue; }
    b=$(stat -c '%a' "$f")
    if chmod 0644 "$f" 2>>"$LIVE_LOG"; then
      log "disable $s: $b -> $(stat -c '%a' "$f")"
    else
      log "disable $s: chmod failed, still $(stat -c '%a' "$f")"
    fi
  done

  for s in acpid mysqld; do
    f="$TARGET_ROOT/etc/rc.d/rc.$s"
    [ -f "$f" ] || continue
    chmod +x "$f"
  done

  if [ "$SSH_ENABLE" = "yes" ]; then
    mkdir -p "$TARGET_ROOT/etc/ssh"
    cat > "$TARGET_ROOT/etc/ssh/sshd_config" <<'H'
Port __SSH_PORT__
AddressFamily inet
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
PermitRootLogin yes
PubkeyAuthentication yes
PasswordAuthentication yes
PermitEmptyPasswords no
UsePAM yes
KbdInteractiveAuthentication no
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
PermitTunnel no
GatewayPorts no
PermitUserEnvironment no
SyslogFacility AUTH
LogLevel INFO
UseDNS no
LoginGraceTime 30
MaxAuthTries 3
MaxSessions 5
Subsystem sftp /usr/libexec/sftp-server
H
    sed -i "s/__SSH_PORT__/${SSH_PORT:-62222}/" "$TARGET_ROOT/etc/ssh/sshd_config"
    chmod 600 "$TARGET_ROOT/etc/ssh/sshd_config"
    local kt keygen=0
    for kt in ed25519 rsa ecdsa; do
      [ -f "$TARGET_ROOT/etc/ssh/ssh_host_${kt}_key" ] || keygen=1
    done
    if [ "$keygen" = "1" ]; then
      chroot "$TARGET_ROOT" ssh-keygen -A >>"$LIVE_LOG" 2>&1
    fi
    chmod 700 "$TARGET_ROOT/etc/ssh"
    local hk
    for hk in "$TARGET_ROOT/etc/ssh/"ssh_host_*_key; do
      [ -f "$hk" ] || continue
      chmod 600 "$hk"
    done
    for hk in "$TARGET_ROOT/etc/ssh/"ssh_host_*_key.pub; do
      [ -f "$hk" ] || continue
      chmod 644 "$hk"
    done
    if [ -f "$TARGET_ROOT/etc/rc.d/rc.sshd" ]; then
      chmod +x "$TARGET_ROOT/etc/rc.d/rc.sshd"
    fi
  else
    if [ -f "$TARGET_ROOT/etc/rc.d/rc.sshd" ]; then
      chmod -x "$TARGET_ROOT/etc/rc.d/rc.sshd"
    fi
  fi

  if [ -f "$TARGET_ROOT/etc/php.ini" ]; then
    local ext
    for ext in dba enchant ftp ldap odbc pdo_odbc shmop snmp soap tidy; do
      sed -i "s|^extension=${ext}\$|;extension=${ext}|"        "$TARGET_ROOT/etc/php.ini"
      sed -i "s|^extension=${ext}\.so\$|;extension=${ext}.so|" "$TARGET_ROOT/etc/php.ini"
    done
  fi

  if [ -d "$ISO_SRC/install/install-overlay" ]; then
      cp -a "$ISO_SRC/install/install-overlay/." "$TARGET_ROOT/"
      log "Install overlay applied."
  fi

  if [ -f "$ISO_SRC/AMOS-GPG-KEY" ]; then
    mkdir -p "$TARGET_ROOT/etc/amos/gpg"
    install -m 644 -o 0 -g 0 "$ISO_SRC/AMOS-GPG-KEY" "$TARGET_ROOT/etc/amos/gpg/AMOS-GPG-KEY"
    install -m 644 -o 0 -g 0 "$ISO_SRC/AMOS-GPG-KEY" "$TARGET_ROOT/root/AMOS-GPG-KEY"
  fi

  local append root_arg
  append="cgroup_no_v1=all lockdown=confidentiality ima_appraise=${IMA_APPRAISE} video=${VIDEO_RES} quiet loglevel=3"
  # rc.S handles ZRAM automatically and gives 3.8GB of compressed swap. No need for ZSWAP
  # Because ZRAM has a higher priority, the system fills up the 3.8GB of ZRAM first. If it overflows, it goes to the /swapfile. With zswap.enabled=1, the kernel will compress those pages again in RAM before writing them to /swapfile.
  # It's a double-compression and waste of CPU. These flags are asking the CPU to compress data for ZRAM, and then if that fills up, asking the CPU to compress it again for ZSWAP before it hits the disk.
  # zswap.enabled=1 zswap.compressor=lz4 zswap.max_pool_percent=${ZSWAP_MAX_POOL}
  if [ "${MANUAL_LAYOUT:-no}" = "yes" ]; then
    if [ "$USE_LVM" = "yes" ]; then
      # MANUAL_ROOT is the LV the user selected; LVM autoactivation
      # recreates the same path at boot once the container is unlocked.
      root_arg="$MANUAL_ROOT"
    elif [ "$ENCRYPT" = "yes" ] && [ -n "$LUKS_NAME" ]; then
      # Plain LUKS: MANUAL_ROOT is the live mapper alias (cryptroot),
      # but the initrd creates it under mkinitrd's convention.
      root_arg="/dev/mapper/$LUKS_NAME"
    else
      root_arg="$MANUAL_ROOT"
    fi
  elif [ "$USE_LVM" = "yes" ]; then
    root_arg="/dev/$VG_NAME/$LV_NAME"
  elif [ "$ENCRYPT" = "yes" ]; then
    root_arg="/dev/mapper/$LUKS_NAME"
  else
    root_arg="$ROOT_PART"
  fi

  if [ "$ENCRYPT" = "yes" ] && [ -n "$LUKS_PART" ]; then
    luks_uuid=$(blkid -s UUID -o value "$LUKS_PART")
    if [ -n "$luks_uuid" ]; then
      append="$append cryptdevice=UUID=${luks_uuid}:${LUKS_NAME}"
      log "boot args: cryptdevice=UUID=$luks_uuid:$LUKS_NAME"
    fi
  fi

  printf '%s\n%s\n' "$append" "$root_arg" > /tmp/amos-boot-args
  log "boot args: root=$root_arg"
  log "System configuration complete."
}


exec_disable_modules() {
  local conf="$TARGET_ROOT/etc/modprobe.d/amos-hardening.conf"
  mkdir -p "$(dirname "$conf")"

  cat > "$conf" <<'EOF'
# AM·OS: kernel modules blacklisted at install time.
#
# Each module below lacks the GNU_PROPERTY_X86_FEATURE_1_IBT marker in
# its .note.gnu.property section. On an IBT-enabled kernel this means
# the kernel cannot apply IBT sealing to the module's code. The module
# still loads and its endbr64 instructions are still present; what is
# missing is the extra hardening step the kernel applies to modules
# that declare themselves IBT-clean.
#
# The "blacklist" directive prevents automatic loading by udev and the
# kernel's module autoloading. An explicit "modprobe <name>" still
# works, so a user who wants a specific module can load it for the
# current session without editing this file.
#
# To re-enable a module permanently: delete or comment out its line
# below, and rebuild the initrd if the module is needed at boot.
#
# The AES kernel modules (aes-x86_64, aesni-intel, etc.) are NOT
# blacklisted. They pass the hardening audit and are required for the
# LUKS AES-XTS configuration this system uses.
#
# See /root/README-HARDENING.txt for the full explanation.

# Hardware-accelerated virtualization.
blacklist kvm-intel
blacklist kvm-amd

# Alternative block ciphers. None are used by this system's LUKS,
# which uses AES-XTS.
blacklist sm4-aesni-avx-x86_64
blacklist sm4-aesni-avx2-x86_64
blacklist aria-gfni-avx512-x86_64
blacklist aria-aesni-avx-x86_64
blacklist aria-aesni-avx2-x86_64
blacklist twofish-x86_64-3way
blacklist twofish-avx-x86_64
blacklist camellia-aesni-avx-x86_64
blacklist camellia-aesni-avx2
blacklist serpent-avx-x86_64
blacklist serpent-avx2
blacklist cast5-avx-x86_64
blacklist cast6-avx-x86_64
blacklist blowfish-x86_64
blacklist aegis128-aesni

# Rare hash helper and rare network driver.
blacklist libsm3
blacklist libnh
blacklist lan966x-pci
EOF
  chmod 644 "$conf"

  log "Kernel modules blacklisted."
}

exec_install_docs() {
  if [ -d "$ISO_SRC/audit" ]; then
    local f base
    for f in "$ISO_SRC/audit"/*.TXT "$ISO_SRC/audit"/*.txt; do
      [ -f "$f" ] || continue
      base=$(basename "$f")
      install -m 644 -o 0 -g 0 "$f" "$TARGET_ROOT/root/$base"
      log "Installed /root/$base"
    done
  else
    warn "audit/ not found on ISO; no audit documentation installed."
  fi

  if [ -d "$ISO_SRC/tools" ]; then
    mkdir -p "$TARGET_ROOT/usr/sbin"
    local f base
    for f in "$ISO_SRC/tools"/*; do
      [ -f "$f" ] || continue
      base=$(basename "$f")
      install -m 755 -o 0 -g 0 "$f" "$TARGET_ROOT/usr/sbin/$base"
      log "Installed /usr/sbin/$base"
    done
  else
    warn "tools/ not found on ISO; no helper tools installed."
  fi
}


exec_postinstall() {
  chroot "$TARGET_ROOT" /sbin/ldconfig >>"$LIVE_LOG" 2>&1 || warn "ldconfig failed"

  if [ -x "$TARGET_ROOT/usr/sbin/update-ca-certificates" ]; then
    log "Running update-ca-certificates..."
    
    # Temporarily replace the target's broken chmod with BusyBox
    # update-ca-certificates runs inside the target chroot and hits the
    # fchmodat2 syscall bug on old kernels.
    local chmod_bins=("/usr/bin/chmod" "/bin/chmod")
    local target_chmods=()
    for cb in "${chmod_bins[@]}"; do
      if [ -f "$TARGET_ROOT$cb" ] && [ ! -L "$TARGET_ROOT$cb" ]; then
        mv "$TARGET_ROOT$cb" "$TARGET_ROOT$cb.bak"
        cp -a /bin/busybox "$TARGET_ROOT$cb"
        target_chmods+=("$cb")
      fi
    done

    # Run the CA update
    chroot "$TARGET_ROOT" /usr/sbin/update-ca-certificates --fresh >>"$LIVE_LOG" 2>&1 || warn "update-ca-certificates failed"

    # Restore the original chmod binaries
    for cb in "${target_chmods[@]}"; do
      mv "$TARGET_ROOT$cb.bak" "$TARGET_ROOT$cb"
    done
  fi
}

exec_mariadb() {
  local uid gid
  uid=$(awk -F: '$1=="mysql"{print $3}' "$TARGET_ROOT/etc/passwd")
  gid=$(awk -F: '$1=="mysql"{print $4}' "$TARGET_ROOT/etc/passwd")

  [ -n "$uid" ] || { warn "mysql user not found, skipping MariaDB."; return 0; }
  [ -n "$gid" ] || gid="$uid"

  mkdir -p "$TARGET_ROOT/tmp" "$TARGET_ROOT/var/lib/mysql"
  chmod 1777 "$TARGET_ROOT/tmp"
  chown -R "$uid:$gid" "$TARGET_ROOT/var/lib/mysql"
  chmod 750 "$TARGET_ROOT/var/lib/mysql"

  set +e

  pflog() { printf '%s\n' "$*" >> "$LIVE_LOG"; }
  pflog "=== MariaDB pre-flight START ==="
  log "cmdline:    $(cat /proc/cmdline)"
  log "lsm active: $(cat /sys/kernel/security/lsm 2>&1)"

  # The root inode of the freshly-formatted filesystem can end up at
  # 0750 rather than 0755, and a non-root process that chroots into
  # this filesystem needs the x bit on the chroot root itself before
  # it can attempt to exec anything inside. exec_mount already fixes
  # this; the chmod here is defence in depth against anything between
  # exec_mount and this point changing the mode.
  chmod 755 "$TARGET_ROOT"

  if ! chroot --userspec="$uid:$gid" "$TARGET_ROOT" /bin/bash -c \
        'touch /tmp/.amos-pf.$$ && rm -f /tmp/.amos-pf.$$' 2>/dev/null; then
    die "uid $uid cannot write to /tmp inside the target. See $LIVE_LOG."
  fi
  if ! chroot --userspec="$uid:$gid" "$TARGET_ROOT" /bin/bash -c \
        'touch /var/lib/mysql/.amos-pf.$$ && rm -f /var/lib/mysql/.amos-pf.$$' 2>/dev/null; then
    die "uid $uid cannot write to /var/lib/mysql inside the target. See $LIVE_LOG."
  fi
  if ! chroot --userspec="$uid:$gid" "$TARGET_ROOT" /bin/true 2>/dev/null; then
    die "uid $uid cannot execute inside the target. See $LIVE_LOG."
  fi

  log "MariaDB pre-flight: uid $uid can write to /tmp and /var/lib/mysql, and exec /bin/true"
  pflog "=== MariaDB pre-flight END ==="
  set -e
  MYSQL_ROOT_PW=""
  while [ ${#MYSQL_ROOT_PW} -lt 42 ]; do
    MYSQL_ROOT_PW=$(chroot "$TARGET_ROOT" /bin/bash -c \
      "head -c 1024 /dev/urandom | tr -dc 'A-Za-z0-9' | head -c 42")
  done
  MYSQL_ROOT_PW="${MYSQL_ROOT_PW:0:42}"
  [ ${#MYSQL_ROOT_PW} -eq 42 ] \
    || die "MariaDB password generation failed (got ${#MYSQL_ROOT_PW} chars, expected 42)."

  mkdir -p "$TARGET_ROOT/tmp"
  chmod 1777 "$TARGET_ROOT/tmp"
  log "MariaDB: /tmp is $(stat -c '%a %u:%g' "$TARGET_ROOT/tmp")"

  if [ ! -d "$TARGET_ROOT/var/lib/mysql/mysql" ]; then
    mkdir -p "$TARGET_ROOT/var/lib/mysql"
    chown -R "$uid:$gid" "$TARGET_ROOT/var/lib/mysql"
    chmod 750 "$TARGET_ROOT/var/lib/mysql"
    log "MariaDB: /var/lib/mysql is $(stat -c '%a %u:%g' "$TARGET_ROOT/var/lib/mysql")"

    if chroot "$TARGET_ROOT" /usr/bin/mariadb-install-db --user=mysql \
         --basedir=/usr --datadir=/var/lib/mysql \
         --auth-root-authentication-method=normal \
         > /tmp/mariadb-init.log 2>&1; then
      log "mariadb-install-db: system tables created"
    else
      warn "mariadb-install-db failed"
      sed 's/^/    mariadb-init: /' /tmp/mariadb-init.log >> "$LIVE_LOG"
    fi
  fi

  [ -d "$TARGET_ROOT/var/lib/mysql/mysql" ] \
    || die "MariaDB system tables missing after initialisation. See /tmp/mariadb-init.log."

  mkdir -p "$TARGET_ROOT/etc/my.cnf.d"
  cat > "$TARGET_ROOT/etc/my.cnf.d/zz-amos-bind.cnf" <<'H'
[mysqld]
bind-address = 10.200.2.1
H
  chmod 644 "$TARGET_ROOT/etc/my.cnf.d/zz-amos-bind.cnf"

  mkdir -p "$TARGET_ROOT/run/mysql"
  chown "$uid:$gid" "$TARGET_ROOT/run/mysql"

  dlg_info "MariaDB" "Starting MariaDB server for first-time setup..."
  chroot "$TARGET_ROOT" /usr/libexec/mariadbd --user=mysql --skip-networking \
    --socket=/run/mysql/mysql.sock --datadir=/var/lib/mysql \
    --pid-file=/run/mysql/mysql.pid >/dev/null 2>&1 &
  MARIADBD_PID=$!

  local ready=0 i
  for i in $(seq 1 30); do
    [ -S "$TARGET_ROOT/run/mysql/mysql.sock" ] && { ready=1; break; }
    sleep 1
  done
  if [ "$ready" != "1" ]; then
    kill "$MARIADBD_PID" 2>/dev/null || true
    MARIADBD_PID=""
    warn "mariadbd did not start; see /tmp/mariadbd-install.log"
    sed 's/^/    mariadbd: /' /tmp/mariadbd-install.log 2>/dev/null | head -20 >> "$LIVE_LOG" || true
    die "MariaDB failed to start after initialisation. Cannot continue."
  fi

  dlg_info "MariaDB" "Setting root password and hardening..."

  chroot "$TARGET_ROOT" /usr/bin/mariadb --socket=/run/mysql/mysql.sock \
    -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${MYSQL_ROOT_PW}';"

  chroot "$TARGET_ROOT" /usr/bin/mariadb --socket=/run/mysql/mysql.sock \
    -u root -p"${MYSQL_ROOT_PW}" 2>>"$LIVE_LOG" <<'H'
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost','127.0.0.1','::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%';
FLUSH PRIVILEGES;
H

  if ! chroot "$TARGET_ROOT" /usr/bin/mariadb --socket=/run/mysql/mysql.sock \
      -u root -p"${MYSQL_ROOT_PW}" \
      -e "CREATE USER IF NOT EXISTS 'root'@'10.200.2.2' IDENTIFIED BY '${MYSQL_ROOT_PW}'; \
          GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.200.2.2' WITH GRANT OPTION; \
          FLUSH PRIVILEGES;" >>"$LIVE_LOG" 2>&1; then
    die "Failed to create root@10.200.2.2"
  fi

  dlg_info "MariaDB" "Shutting down install-time server..."
  chroot "$TARGET_ROOT" /usr/bin/mariadb-admin --socket=/run/mysql/mysql.sock \
    -u root -p"${MYSQL_ROOT_PW}" shutdown >/dev/null 2>&1 || kill "$MARIADBD_PID" 2>/dev/null || true
  for i in $(seq 1 10); do kill -0 "$MARIADBD_PID" 2>/dev/null || break; sleep 1; done
  kill -0 "$MARIADBD_PID" 2>/dev/null && kill -9 "$MARIADBD_PID" 2>/dev/null || true
  MARIADBD_PID=""
  rm -f "$TARGET_ROOT/run/mysql/mysql.sock" "$TARGET_ROOT/run/mysql/mysql.pid"

  log "MariaDB initialised."
}

exec_initrd() {
  local kver
  kver=$(ls "$TARGET_ROOT/lib/modules/" 2>/dev/null | head -n1)
  [ -n "$kver" ] || { warn "No kernel modules found."; return 0; }

  local gen="/usr/share/mkinitrd/mkinitrd_command_generator.sh"
  [ -f "$TARGET_ROOT$gen" ] \
    || die "mkinitrd_command_generator.sh not found in target"

  local helper="$TARGET_ROOT/usr/local/sbin/amos-geninitrd"
  [ -x "$helper" ] \
    || die "amos-geninitrd not installed; check amos package"

  # Write /etc/default/amos-geninitrd, tailored to this install's
  # storage stack, so amos-geninitrd knows which modules to include.
  local extra_mods="bochs:fbcon:drm:drm_kms_helper"
  if [ "$ENCRYPT" = "yes" ]; then
    extra_mods="${extra_mods}:dm-crypt:dm-mod:aes-x86_64:aes-generic:xts:sha256:sha512"
  fi
  if [ "$ENCRYPT" = "yes" ] && [ "$ENCRYPT_INTEGRITY" = "yes" ]; then
    extra_mods="${extra_mods}:dm-integrity:dm-bufio"
  fi
  if [ "$USE_LVM" = "yes" ]; then
    extra_mods="${extra_mods}:dm-mod:dm-snapshot"
  fi

  mkdir -p "$TARGET_ROOT/etc/default"
  {
    printf '# Written by install.sh. Used by /usr/local/sbin/amos-geninitrd.\n'
    printf 'AMOS_EXTRA_MODS="%s"\n' "$extra_mods"
  } > "$TARGET_ROOT/etc/default/amos-geninitrd"
  chmod 644 "$TARGET_ROOT/etc/default/amos-geninitrd"
  log "initrd: wrote /etc/default/amos-geninitrd (mods=$extra_mods)"

  # --- Shadow 'install' inside target to avoid fchmodat2 bug ---
  # amos-geninitrd uses 'install -m' which fails on older rescue kernels.
  local shadowed_installs=()
  local ib
  for ib in "/usr/bin/install" "/bin/install"; do
    if [ -f "$TARGET_ROOT$ib" ] && [ ! -L "$TARGET_ROOT$ib" ]; then
      mv "$TARGET_ROOT$ib" "$TARGET_ROOT$ib.bak"
      cp /bin/busybox "$TARGET_ROOT$ib"
      shadowed_installs+=("$ib")
    fi
  done
  # --------------------------------------------------------------

  # Delegate the build to the same script that runs on kernel upgrades.
  local out rc
  out=$(chroot "$TARGET_ROOT" env KERNEL="/boot/vmlinuz-$kver" AMOS_INSTALL=1 \
          /usr/local/sbin/amos-geninitrd 2>&1) || rc=$?
  rc=${rc:-0}

  # --- Restore original install binaries ---
  for ib in "${shadowed_installs[@]}"; do
    mv "$TARGET_ROOT$ib.bak" "$TARGET_ROOT$ib"
  done
  # ------------------------------------------

  if [ -n "$out" ]; then
    log "initrd: amos-geninitrd output:"
    printf '%s\n' "$out" | sed 's/^/    /' >> "$LIVE_LOG"
  fi
  [ "$rc" -eq 0 ] || die "amos-geninitrd failed (exit $rc)"

  [ -f "$TARGET_ROOT/boot/initrd.gz" ]  || die "no /boot/initrd.gz after amos-geninitrd"
  [ -s "$TARGET_ROOT/boot/initrd.gz" ]  || die "empty /boot/initrd.gz after amos-geninitrd"

  log "Initrd generated for $kver."
}

exec_bootloader_efi() {
  local elilo="" p
  for p in \
      "$TARGET_ROOT/boot/efi/EFI/AMOS/elilo.efi" \
      "$TARGET_ROOT/boot/efi/EFI/BOOT/BOOTX64.EFI" \
      "$TARGET_ROOT/usr/share/elilo/elilo.efi" \
      "$TARGET_ROOT/usr/share/elilo/elilo-x86_64.efi" \
      "$TARGET_ROOT/boot/elilo-x86_64.efi" \
      "$TARGET_ROOT/boot/elilo64.efi" \
      "$TARGET_ROOT/boot/elilo.efi"; do
    [ -f "$p" ] && { elilo="$p"; break; }
  done
  if [ -z "$elilo" ]; then
    elilo=$(find "$TARGET_ROOT" -maxdepth 5 -type f -iname '*.efi' \
      ! -iname '*ia32*' ! -iname '*i386*' 2>/dev/null | head -n1)
  fi
  [ -n "$elilo" ] || die "elilo.efi not found."

  local efi_slack="$TARGET_ROOT/boot/efi/EFI/AMOS"
  local efi_boot="$TARGET_ROOT/boot/efi/EFI/BOOT"
  mkdir -p "$efi_slack" "$efi_boot"
  cp "$elilo" "$efi_slack/elilo.efi"
  cp "$elilo" "$efi_boot/BOOTX64.EFI"

  local kernel="$TARGET_ROOT/boot/vmlinuz-generic"
  local initrd="$TARGET_ROOT/boot/initrd.gz"
  [ -f "$kernel" ] || die "vmlinuz-generic not found."
  [ -f "$initrd" ] || die "initrd.gz not found."
  cp "$kernel" "$efi_slack/vmlinuz"
  cp "$initrd" "$efi_slack/initrd.gz"
  cp "$kernel" "$efi_boot/vmlinuz"
  cp "$initrd" "$efi_boot/initrd.gz"

  local append root_arg
  append=$(sed -n '1p' /tmp/amos-boot-args)
  root_arg=$(sed -n '2p' /tmp/amos-boot-args)

  cat > "$efi_slack/elilo.conf" <<EOF
prompt
timeout = 3
default = AMOS
image = vmlinuz
  initrd = initrd.gz
  label = AMOS
  read-only
  root = $root_arg
  append = "$append"
EOF
  cp "$efi_slack/elilo.conf" "$efi_boot/elilo.conf"

  if command -v efibootmgr >/dev/null 2>&1; then
    local efi_disk efi_part
    if [ "${MANUAL_LAYOUT:-no}" = "yes" ]; then
      efi_disk="${MANUAL_ESP_DISK:-$TARGET_DISK}"
      efi_part="${MANUAL_ESP_PART:-1}"
    else
      efi_disk="$TARGET_DISK"
      efi_part="1"
    fi
    local efi_out
    if efi_out=$(efibootmgr --create --disk "$efi_disk" --part "$efi_part" \
         --label "AMOS" --loader '\EFI\AMOS\elilo.efi' 2>&1); then
      log "efibootmgr: $efi_out"
    else
      warn "efibootmgr failed: $efi_out"
      warn "efibootmgr could not create an NVRAM entry; relying on"
      warn "the BOOTX64.EFI fallback at /boot/efi/EFI/BOOT/BOOTX64.EFI."
      warn "Most UEFI firmware will find and boot this automatically."
      warn "If it does not, enter the firmware setup and add a boot"
      warn "entry pointing at \\EFI\\AMOS\\elilo.efi on the ESP."
    fi
  fi
  log "EFI bootloader installed."
}

exec_bootloader_bios() {
  local append root_arg
  append=$(sed -n '1p' /tmp/amos-boot-args)
  root_arg=$(sed -n '2p' /tmp/amos-boot-args)

  cat > "$TARGET_ROOT/etc/lilo.conf" <<EOF
boot = $TARGET_DISK
prompt
timeout = 3
default = AMOS
image = /boot/vmlinuz-generic
  initrd = /boot/initrd.gz
  label = AMOS
  read-only
  root = $root_arg
  append = "$append"
EOF
  chroot "$TARGET_ROOT" /sbin/lilo -v >/dev/null
  log "LILO installed."
}

exec_bootloader() {
  if [ "$BOOTMODE" = "efi" ]; then exec_bootloader_efi; else exec_bootloader_bios; fi
}

exec_annode() {
  if [ ! -f "$ISO_SRC/install/annode/setup-annode.sh" ]; then
    if [ -n "$MYSQL_ROOT_PW" ]; then
      {
        printf '# MariaDB root password (generated at install time)\n'
        printf '# No annode setup script was present on the ISO, so there is\n'
        printf '# no node.properties to hold this. Move it into your\n'
        printf '# node configuration before deploying.\n'
        printf 'MARIADB_ROOT_PASSWORD=%s\n' "$MYSQL_ROOT_PW"
      } > "$TARGET_ROOT/root/mariadb_root_password.txt"
      chmod 600 "$TARGET_ROOT/root/mariadb_root_password.txt"
      ANNODE_PW_STORED="/root/mariadb_root_password.txt (fallback; annode not present)"
    fi
    return 0
  fi

  if [ -f "$ISO_SRC/payload/annode/CHECKSUMS.sha256" ] && \
     [ -f "$ISO_SRC/payload/annode/CHECKSUMS.sha256.asc" ] && \
     [ -f "$ISO_SRC/AMOS-GPG-KEY" ]; then
    if ! verify_signed_manifest \
        "$ISO_SRC/payload/annode/CHECKSUMS.sha256" \
        "$ISO_SRC/payload/annode/CHECKSUMS.sha256.asc" \
        "$ISO_SRC/AMOS-GPG-KEY" \
        "$ISO_SRC/payload/annode" \
        sha256sum; then
      die "Annode payload verification failed. See $LIVE_LOG."
    fi
  fi

  # --- Shadow 'chmod' (and 'install') inside target to avoid fchmodat2 bug ---
  # setup-annode.sh uses 'chmod' via chroot, which crashes on older kernels.
  local shadowed_bins=()
  local cb
  for cb in "/usr/bin/chmod" "/bin/chmod" "/usr/bin/install" "/bin/install"; do
    if [ -f "$TARGET_ROOT$cb" ] && [ ! -L "$TARGET_ROOT$cb" ]; then
      mv "$TARGET_ROOT$cb" "$TARGET_ROOT$cb.bak"
      cp /bin/busybox "$TARGET_ROOT$cb"
      shadowed_bins+=("$cb")
    fi
  done
  # ---------------------------------------------------------------------------

  local rc=0
  MYSQL_ROOT_PW="$MYSQL_ROOT_PW" \
  TARGET_ROOT="$TARGET_ROOT" \
  ISO_SRC="$ISO_SRC" \
  ANNODE_DIALOG_MODE=1 \
    bash "$ISO_SRC/install/annode/setup-annode.sh" "$ISO_PROFILE" \
      2>>"$TARGET_ROOT/root/annode-setup-stderr.log" | \
    dialog --title "Installing annode" --gauge "" "$DLG_H" "$DLG_W"
  rc=${PIPESTATUS[0]}
  set -e

  # --- Restore original binaries ---
  for cb in "${shadowed_bins[@]}"; do
    mv "$TARGET_ROOT$cb.bak" "$TARGET_ROOT$cb"
  done
  # ---------------------------------

  if [ "$rc" -ne 0 ]; then
    die "Annode setup failed (rc=$rc). See /root/annode-setup.log on the target."
  fi


  ANNODE_CONF_FILE=$(find "$TARGET_ROOT" -name node.properties -type f -print -quit 2>/dev/null)

  if [ -n "$ANNODE_CONF_FILE" ]; then
    ANNODE_PW_STORED="${ANNODE_CONF_FILE#$TARGET_ROOT}"
    if grep -qF "$MYSQL_ROOT_PW" "$ANNODE_CONF_FILE" 2>/dev/null; then
      log "MariaDB password found in $ANNODE_PW_STORED"
    else
      warn "MariaDB password not found in $ANNODE_PW_STORED"
      ANNODE_PW_STORED="$ANNODE_PW_STORED (password NOT verified)"
    fi
  else
    die "node.properties not found after annode setup; see /root/annode-setup.log on the target."
  fi
}

exec_post_install() {
  local target_script="/usr/sbin/amos-harden"
  local dlg_pid


  if [ ! -f "$TARGET_ROOT$target_script" ]; then
    warn "$target_script not found in target root; skipping"
    warn "Is the 'amos' package part of the install set?"
    return 0
  fi

  if [ ! -x "$TARGET_ROOT$target_script" ]; then
    warn "$target_script is not executable; skipping"
    return 0
  fi

  dialog --title "Finalizing System" --infobox "Applying post-installation hardening...\n\nThis may take a moment." 8 60 &
  dlg_pid=$!
  
  set +e
  chroot "$TARGET_ROOT" /bin/bash "$target_script" --apply "$ISO_PROFILE" > /tmp/post-install-run.log 2>&1
  local ret=$?
  set -e
  
  kill $dlg_pid 2>/dev/null || true
  wait $dlg_pid 2>/dev/null || true
  clear

  if [ "$ret" -ne 0 ]; then
    dialog --title "Error" --msgbox "Post-install configuration failed.\nCheck /tmp/post-install-run.log for details." 10 50
    die "post-install service configuration failed"
  fi
}


issue() {
  cat > "$TARGET_ROOT/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 "$TARGET_ROOT/etc/issue"
  log "issue: Pre-login banner written"
}

issuemotd() {
  if [ -f "$TARGET_ROOT/etc/motd.$ISO_PROFILE" ]; then
    mv "$TARGET_ROOT/etc/motd.$ISO_PROFILE" "$TARGET_ROOT/etc/motd"
    chmod 644 "$TARGET_ROOT/etc/motd"
  fi
  rm -f "$TARGET_ROOT/etc/motd."* 2>/dev/null || true
  issue
}

main() {
  [ "$(id -u)" -eq 0 ] || { echo "Run as root." >&2; exit 1; }
  export AMOS_INSTALL=1
  if mountpoint -q "$TARGET_ROOT" 2>/dev/null; then
    log "Cleaning up stale /target mounts from a previous run."
    for m in "$TARGET_ROOT/mnt/iso" "$TARGET_ROOT/dev/pts" "$TARGET_ROOT/dev" \
             "$TARGET_ROOT/proc" "$TARGET_ROOT/sys" \
             "$TARGET_ROOT/boot/efi" "$TARGET_ROOT/boot" "$TARGET_ROOT"; do
      mountpoint -q "$m" 2>/dev/null && umount -l "$m" 2>/dev/null || true
    done
  fi
  umask 022
  open_tty || { echo "No usable terminal." >&2; exit 1; }

  log "install.sh started at $(date)"

  require_secrets
  preflight
  compute_partition_layout

  if [ "${MANUAL_LAYOUT:-no}" = "yes" ]; then
    dlg_info "Installing" "Using manually-prepared partitions..."
    log "Manual layout; skipping partition and format steps."
  else
    dlg_info "Installing" "Partitioning $TARGET_DISK..."
    exec_partition

    dlg_info "Installing" "Creating filesystems..."
    exec_format
  fi

  dlg_info "Installing" "Mounting target..."
  exec_mount

  dlg_info "Installing" "Verifying packages..."
  exec_verify_packages

  dlg_info "Installing" "Creating temporary swap on target..."
  add_temp_swap

  dlg_info "Installing" "Installing packages. This takes several minutes..."
  exec_install_packages

  dlg_info "Installing" "Configuring the system..."
  exec_system_config
  issuemotd

  dlg_info "Installing" "Applying hardening policy..."
  exec_disable_modules
  exec_sysctl_hardening
  exec_install_docs

  dlg_info "Installing" "Regenerating library cache and CA bundle..."
  exec_postinstall

  dlg_info "Installing" "Generating kernel initrd..."
  exec_initrd

  [ -f "$TARGET_ROOT/boot/initrd.gz" ] \
    || die "initrd.gz was not produced in the target"
  [ -s "$TARGET_ROOT/boot/initrd.gz" ] \
    || die "initrd.gz is empty"
  [ -f "$TARGET_ROOT/boot/vmlinuz-generic" ] \
    || die "vmlinuz-generic missing in the target"

  exec_bootloader

if [[ "$ISO_PROFILE" != "edge" ]]; then
  dlg_info "Installing" "Initializing MariaDB (this may take a minute)..."
  exec_mariadb

  exec_annode

fi

  dlg_info "Installing" "Configuring services..."

  dlg_info "Installing" "Hardening file permissions..."
  exec_post_install

  sync_log_to_target
  sync

  local elapsed=$((SECONDS - START_TIME))
  local em=$((elapsed / 60))
  local es=$((elapsed % 60))
  local pw_line=""
if [[ "$ISO_PROFILE" != "edge" ]]; then
  
  if [ -n "$ANNODE_PW_STORED" ]; then
    pw_line="MariaDB password   $ANNODE_PW_STORED"
  else
    pw_line="MariaDB password   (not persisted)"
  fi
fi

  local enc_line
  if [ "$ENCRYPT" = "yes" ]; then
    if [ "$ENCRYPT_INTEGRITY" = "yes" ]; then
      enc_line="$ENCRYPT (AES-XTS + HMAC-SHA256)"
    else
      enc_line="$ENCRYPT (AES-XTS)"
    fi
  else
    enc_line="$ENCRYPT"
  fi

  log "post-install rc.elogind mode: $(stat -c '%a' "$TARGET_ROOT/etc/rc.d/rc.elogind" 2>/dev/null || echo missing)"


  local summary
  summary=$(cat <<EOF

  AM·OS is installed.

  Hostname      $TARGET_HOSTNAME
  Disk          $TARGET_DISK
  Boot mode     $BOOTMODE
  Filesystem    $FSTYPE
  Encryption    $enc_line
  LVM           $USE_LVM
  SSH           $SSH_ENABLE (from $SSH_ALLOW_FROM)
  Timezone      $TIMEZONE
  Duration      ${em}m ${es}s

  $pw_line

Next steps:
    1. Shut down or reboot the machine
    2. If the installation media is set to boot before the internal
       disk, remove or eject it
    3. Boot from the installed disk

  If you installed AM·OS using the chroot method in rescue mode, 
  select "no" and then exit the chroot environment. Choose the 
  option to boot from disk in your hosting provider's control panel, 
  and then reboot the server.

  Logs on the installed system:
    $TARGET_LOG_REL
    /root/AMOS-GPG-KEY

  Documentation:
    /root/README-HARDENING.txt
    /root/README-STORAGE.txt
    /root/AUDIT.TXT

  HARDENING NOTICE
  ----------------
  For your security, AM·OS has disabled (blacklisted) 20 kernel
  modules that had a hardening weakness in how they declare
  themselves to the kernel. These include:

    - Hardware-accelerated virtualization (kvm-intel, kvm-amd)
    - Several alternative block ciphers (Serpent, Twofish, CAST5/6,
      Camellia, ARIA, SM4, Blowfish, AEGIS-128)
    - Two rare hash helpers (libsm3, libnh)
    - A rare network driver (lan966x-pci)

  Everything on a normal system still works, and encrypted disks
  (if enabled) are unaffected: LUKS uses AES-XTS with AES-NI hardware
  acceleration, which is not on the blacklist.

  If you specifically need one of these modules (for example,
  kvm-intel to run virtual machines), you can re-enable it at your
  own risk. The full explanation and the step-by-step re-enable
  instructions are in:

      /root/README-HARDENING.txt

  In short, edit /etc/modprobe.d/amos-hardening.conf as
  root, comment out the line for the module you want, then run
  "modprobe <module>" or reboot. You can also load a module for a
  single session with "modprobe <module>" without editing anything.

  Remove the installation media before rebooting.
EOF
)

  if dlg_yesno "Installation complete" "$summary

  Reboot now?"; then
    sync
    cleanup
    close_tty
    setsid sh -c 'sleep 2; sync; reboot -f || echo b > /proc/sysrq-trigger' \
        </dev/null >/dev/null 2>&1 &

    pkill -x dropbear 2>/dev/null || true
  else
    dlg_msg "Stopped" "You may reboot manually when ready."
  fi
}

main "$@"