#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script 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.
#
set -eu
export LANG=C.utf8
export LC_ALL=C.utf8
export NCURSES_NO_UTF8_ACS=1

trap 'echo "Setup interrupted." >&2; exit 1' INT TERM

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=common.sh
. "$SCRIPT_DIR/common.sh"

_sanitize() {
    printf '%s' "$1" | head -n1 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
}

: > "$LIVE_LOG"

TARGET_DISK=""
BOOTMODE="auto"
FSTYPE="ext4"
ENCRYPT="no"
ENCRYPT_INTEGRITY="no"
USE_LVM="no"
LUKS_PASSPHRASE=""
TARGET_HOSTNAME="amos"
ROOT_PASSWORD=""
USER_NAME=""
USER_PASSWORD=""
SSH_ENABLE="yes"
SSH_ALLOW_FROM="10.0.2.2/32"
SSH_PORT="62222"
NETWORK_MODE="dhcp"
NETWORK_IFACE=""
NETWORK_IP=""
NETWORK_GATEWAY=""
NETWORK_DNS=""
TIMEZONE="UTC"
KEYMAP=""
MODE="advanced"
ISO_SRC=""

ESP_SIZE_MIB=1024
BOOT_SIZE_MIB=1024
SWAP_SIZE_MIB=2048
VIDEO_RES="1280x720-32"
ZSWAP_MAX_POOL=20
LUKS_NAME="cryptroot"
VG_NAME="vg0"
LV_NAME="root"
# Percentage of free extents in the VG allocated to the root LV.
# The remainder is reserved so the user can take an LVM snapshot
# before a risky upgrade and roll back if something breaks. 100
# would fill the VG entirely, leaving no room for snapshots.
LVM_ROOT_PERCENT=90
LVM_DATA_ENABLE="no"
LVM_DATA_SIZE_MIB=0
LVM_DATA_NAME="data"
LVM_DATA_MOUNT=""

CONFIG_FILE="/root/amos-install.conf"

WIZ_STEPS=()

detect_bootmode() {
  if [ -d /sys/firmware/efi ]; then BOOTMODE="efi"; else BOOTMODE="bios"; fi
}

detect_iso_source() {
  local c
  for c in /var/log/mount /mnt/cdrom /media/cdrom /mnt/sr0 /mnt /mnt/iso; do
    [ -d "$c/$PKGMAIN" ] && { ISO_SRC="$c"; return 0; }
  done
  echo "Looked for $PKGMAIN/ under: /var/log/mount /mnt/cdrom /media/cdrom /mnt/sr0 /mnt /mnt/iso" >&2
  return 1
}

# ---------------------------------------------------------------------------
#  Wizard steps
#
#  Each function returns:
#    0  proceed to next step
#    3  go back to previous step
#
#  IMPORTANT: steps must always present at least one dialog. A step that
#  returns 0 without user interaction traps the wizard's backward
#  navigation in an infinite loop: Back -> silent step -> advance -> Back.
#  Conditional steps are filtered out of the step list at build time
#  (see _build_steps) rather than being executed as no-ops.
# ---------------------------------------------------------------------------

ui_mode() {
  local choice rc
  choice=$(dlg_menu_nav "Installation mode" \
"\n  Choose how much control you want over the installation.

  Quick mode picks sensible defaults: ext4 root, no encryption,
  no LVM, DHCP, no SSH, UTC timezone. You will be asked only for
  the target disk and a root password.

  Advanced mode walks through every option." \
    20 72 4 \
    "quick"    "Automatic with sensible defaults" \
    "advanced" "Full control over every option" \
    "manual"   "Drop to a shell for custom partitioning")
  rc=$?
  case $rc in
    0) choice=$(_sanitize "$choice")
       MODE="${choice:-advanced}"
       log "Mode: $MODE"
       # Quick mode silently applies these defaults here rather than
       # as a no-op step, which would break backward navigation.
       if [ "$MODE" = "quick" ]; then
         FSTYPE="ext4"
         ENCRYPT="no"
         ENCRYPT_INTEGRITY="no"
         USE_LVM="no"
         USER_NAME=""
         # NETWORK_MODE / NETWORK_IFACE are set by ui_network, which is
         # in the quick-mode step list. Do not pre-set them here.
         TIMEZONE="UTC"
         if [ "$SLIRP" = "yes" ]; then
           SSH_ENABLE="yes"
           SSH_ALLOW_FROM="${SSH_ALLOW_FROM:-10.0.2.2/32}"
           SSH_PORT="${SSH_PORT:-62222}"
           log "SSH: auto-enabled for slirp NAT (from $SSH_ALLOW_FROM)"
         fi
       fi
       return 0 ;;
    *) return 3 ;;
  esac
}

ui_keymap() {
  local root="/usr/share/kbd/keymaps"
  local i386="$root/i386"
  local families="azerty bepo carpalx colemak dvorak fgGIod neo olpc qwerty qwertz"

  [ -d "$i386" ] || { KEYMAP="i386/qwerty/us"; return 0; }

  local -a priority=(
    "qwerty/us|English (US)"
    "qwerty/uk|English (UK)"
    "azerty/fr|French (AZERTY)"
    "qwertz/de|German (QWERTZ)"
    "qwerty/es|Spanish"
    "qwerty/it|Italian"
    "qwerty/pt|Portuguese"
    "qwerty/nl|Dutch"
    "qwerty/pl|Polish"
    "qwerty/cz-lat2|Czech"
    "qwertz/hu|Hungarian"
    "qwerty/trq|Turkish (Q)"
    "qwerty/trf|Turkish (F)"
    "qwerty/ru|Russian"
    "qwerty/gr|Greek"
    "qwerty/ar|Arabic"
    "dvorak/dvorak|Dvorak"
    "colemak/en-latin9|Colemak"
  )

  local -a entries=()
  local -a pinned=()
  local entry path desc rel

  for entry in "${priority[@]}"; do
    path="${entry%%|*}"
    desc="${entry##*|}"
    [ -f "$i386/$path.map.gz" ] || continue
    pinned+=("$path")
    entries+=("$path" "$desc")
  done

  local pinned_str=" ${pinned[*]} "

  while IFS= read -r rel; do
    [ -n "$rel" ] || continue
    case "$pinned_str" in
      *" $rel "*) continue ;;
    esac
    entries+=("$rel" "")
  done < <(cd "$i386" && \
           find $families -name '*.map.gz' 2>/dev/null \
           | sed 's|\.map\.gz$||' \
           | sort)

  local n_items=$(( ${#entries[@]} / 2 ))
  log "Keymap menu: $n_items items ($(( ${#pinned[@]} )) pinned)"

  local choice rc
  choice=$(dlg_menu_nav "Keyboard layout" \
    "\n  Select the keyboard layout for the installed system.\n\n  The most common layouts are listed first.\n  Everything else follows alphabetically.\n  Type the first letters of a path to jump to it.\n" \
    24 68 18 "${entries[@]}")
  rc=$?
  case $rc in
    0) choice=$(_sanitize "$choice")
       [ -z "$choice" ] && KEYMAP="i386/qwerty/us" || KEYMAP="i386/$choice"
       log "Keymap: $KEYMAP"
       return 0 ;;
    *) return 3 ;;
  esac
}

list_disks() {
  local tmp line name size type model
  tmp=$(mktemp)
  if ! lsblk -d -n -o NAME,SIZE,TYPE,MODEL 2>/dev/null > "$tmp"; then
    rm -f "$tmp"
    return 0
  fi
  while IFS= read -r line; do
    name=$(printf '%s\n' "$line" | awk '{print $1}')
    size=$(printf '%s\n' "$line" | awk '{print $2}')
    type=$(printf '%s\n' "$line" | awk '{print $3}')
    model=$(printf '%s\n' "$line" | awk '{$1=$2=$3=""; sub(/^ +/, ""); print}')
    [ "$type" = "disk" ] || continue
    case "$name" in
      loop*|sr*|ram*|zram*|dm-*) continue ;;
    esac
    printf '%s\t%s %s\n' "/dev/$name" "$size" "$model"
  done < "$tmp"
  rm -f "$tmp"
}

ui_disk() {
  local -a lines=()
  local dev meta
  while IFS=$'\t' read -r dev meta; do
    [ -n "$dev" ] || continue
    lines+=("$dev" "$meta")
  done < <(list_disks)

  if [ ${#lines[@]} -eq 0 ]; then
    dlg_error "No physical disks detected."
    exit 1
  fi

  local n_disks=$(( ${#lines[@]} / 2 ))

  local partition_layout
  if [ "$BOOTMODE" = "efi" ]; then
    partition_layout="a FAT32 EFI System Partition and an ext4 root partition"
  else
    partition_layout="a single ext4 root partition"
  fi

  local rc
  if [ "$n_disks" -eq 1 ]; then
    TARGET_DISK="${lines[0]}"
    dlg_yesno_nav "Target disk" \
"\n  Only one physical disk was detected:

      $TARGET_DISK
      ${lines[1]}

  The installer will:

    - Wipe the disk and create a fresh partition table
    - Create $partition_layout
    - Create a $SWAP_SIZE_MIB MiB swap file on root
      (not a separate partition)

  ALL DATA ON $TARGET_DISK WILL BE PERMANENTLY DESTROYED.

  For encryption, LVM, a different filesystem, or to
  prepare partitions yourself, choose advanced or
  manual mode in the previous step.

  Continue?"
    rc=$?
    case $rc in
      0) : ;;
      1) dlg_msg "Cancelled" "Installation aborted. Nothing has been changed."; exit 0 ;;
      *) return 3 ;;
    esac
  else
    local choice
    choice=$(dlg_menu_nav "Target disk" \
      "\n  Select the disk that AM·OS will be installed onto.\n\n  Layout:  $partition_layout\n           plus a $SWAP_SIZE_MIB MiB swap file on root.\n\n  ALL DATA ON THE SELECTED DISK WILL BE DESTROYED.\n" \
      22 76 10 "${lines[@]}")
    rc=$?
    case $rc in
      0) choice=$(_sanitize "$choice")
         [ -n "$choice" ] || { dlg_error "Disk selection cancelled."; return 3; }
         TARGET_DISK="$choice" ;;
      *) return 3 ;;
    esac
  fi

  log "Target disk: $TARGET_DISK"

  local size_b
  if ! size_b=$(blockdev --getsize64 "$TARGET_DISK" 2>/dev/null); then
    dlg_error "Cannot read size of $TARGET_DISK."
    exit 1
  fi
  if [ "$size_b" -lt 10737418240 ]; then
    dlg_error "Disk smaller than 10 GB. AM·OS will not fit."
    exit 1
  fi

  if grep -q "^${TARGET_DISK}[0-9p]" /proc/mounts 2>/dev/null; then
    local mounts
    mounts=$(grep "^${TARGET_DISK}[0-9p]" /proc/mounts | awk '{print "    " $1 " -> " $2}' | head -6)
    [ -n "$mounts" ] || mounts="    (mount list changed; re-run setup)"
    dlg_yesno_nav "Disk in use" \
"\n  $TARGET_DISK has partitions that are currently mounted:

${mounts}

  The installer needs these unmounted before it can proceed.

  Unmount them now and continue? (Any filesystem not
  cleanly unmounted may be left in an inconsistent state.)"
    rc=$?
    case $rc in
      0) : ;;
      1) dlg_msg "Cancelled" "Installation aborted. Nothing has been changed."; exit 0 ;;
      *) return 3 ;;
    esac
    local mnt
    while IFS= read -r mnt; do
      umount "$mnt" 2>/dev/null || true
    done < <(grep "^${TARGET_DISK}[0-9p]" /proc/mounts | awk '{print $2}')
    if grep -q "^${TARGET_DISK}[0-9p]" /proc/mounts 2>/dev/null; then
      dlg_error "Could not unmount all partitions of $TARGET_DISK."
      exit 1
    fi
    log "User confirmed unmount of $TARGET_DISK partitions."
  fi
  return 0
}

ui_fstype() {
  local -a entries=("ext4" "ext4 - default" on)
  command -v mkfs.xfs   >/dev/null 2>&1 && entries+=("xfs"   "xfs - high performance" off)
  command -v mkfs.btrfs >/dev/null 2>&1 && entries+=("btrfs" "btrfs - snapshotting filesystem" off)
  local choice rc
  choice=$(dlg_radiolist_nav "Root filesystem" \
    "\n  Choose filesystem (space to select).\n" \
    15 72 5 "${entries[@]}")
  rc=$?
  case $rc in
    0) choice=$(_sanitize "$choice")
       FSTYPE="${choice:-ext4}"
       log "Filesystem: $FSTYPE"
       return 0 ;;
    *) return 3 ;;
  esac
}

ui_encryption() {
  local rc
  while :; do
    dlg_yesno_nav "Disk encryption" \
"\n  Encrypt the root filesystem with LUKS?
  
  If installing in a datacenter, you will need a KVM console or
  VNC access or an equivalent.  When enabled, you will be prompted 
  for the encryption passphrase every time the machine boots. 
  
  Choose No for an unencrypted install."
    rc=$?
    case $rc in
      0)
        ENCRYPT="yes"
        log "Encryption: yes"
        if prompt_luks_passphrase; then
          return 0
        fi
        # Back from passphrase prompt: loop back to yes/no so the
        # user can change their answer rather than jumping past this
        # step entirely.
        continue
        ;;
      1)
        ENCRYPT="no"
        log "Encryption: no"
        return 0
        ;;
      *)
        return 3
        ;;
    esac
  done
}

ui_encryption_integrity() {
  local rc
  dlg_yesno_nav_defaultno "Tamper detection" \
"\n  Add tamper detection to the encrypted container?

  This feature is marked experimental upstream. Trade-offs are
  listed below.

  AES-XTS encrypts the disk but does not detect tampering. If an
  attacker with raw disk access modifies the ciphertext, the kernel
  returns garbage rather than an error, and the filesystem may
  silently corrupt or misbehave.

  Tamper detection writes a cryptographic tag alongside every sector.
  A modified sector fails verification, and the kernel returns an
  I/O error instead of garbage.

  Trade-offs:

    * Detection.   Silent corruption becomes a loud error.
    * Performance. Write throughput is roughly halved. Every write
                   is journaled twice so the data and its tag stay
                   in sync.
    * Space.       ~0.8% of the disk is reserved for tags.
    * Maturity.    cryptsetup marks this feature EXPERIMENTAL. The
                   label dates to kernel 4.12 (2017); in practice
                   the code is widely used and stable.

  Continue with tamper detection enabled?"
  rc=$?
  case $rc in
    0) ENCRYPT_INTEGRITY="yes"; log "Integrity: yes"; return 0 ;;
    1) ENCRYPT_INTEGRITY="no";  log "Integrity: no";  return 0 ;;
    *) return 3 ;;
  esac
}

ui_lvm() {
  local text rc
  text="$(cat <<'EOF'

  Use LVM (Logical Volume Manager)?

    LVM is layer between the disk and the filesystem. Instead of one
    big partition holding the root filesystem, LVM carves the partition
    into a "volume group" and allocates "logical volumes" from it.

   With LVM you can:
    * Resize the root filesystem later without repartitioning.
    * Snapshot the filesystem before risky upgrades, roll back if
      something breaks.
    * Multiple filesystems (root, home, var) sharing one pool.

  It's not needed for a simple single-disk server or workstation.
EOF
)"
  dlg_yesno_nav "Logical Volume Manager" "$text"
  rc=$?
  case $rc in
    0) USE_LVM="yes"; log "LVM: yes"; return 0 ;;
    1) USE_LVM="no";  log "LVM: no";  return 0 ;;
    *) return 3 ;;
  esac
}

ui_lvm_data() {
  [ "$USE_LVM" = "yes" ] || return 0

  local rc
  dlg_yesno_nav "Data volume" \
"\n  Create a second logical volume?

  LVM can host more than one filesystem. A second volume can hold
  data you want to isolate from the root filesystem. For example,
  a large database directory, an application's storage, or files
  you plan to back up on their own schedule.

  Benefits:

    * A runaway process cannot fill the root filesystem.
    * The volume can be resized independently.
    * Snapshot and restore just that volume, without touching root.

  The volume group is split three ways: this data volume, the root
  volume, and a 10% reserve for snapshots.

  Create a second logical volume?"
  rc=$?
  case $rc in
    0) LVM_DATA_ENABLE="yes" ;;
    1) LVM_DATA_ENABLE="no"; log "LVM data volume: no"; return 0 ;;
    *) return 3 ;;
  esac

  local disk_mib vg_mib avail_mib default_data_mib size_in
  disk_mib=$(( $(blockdev --getsize64 "$TARGET_DISK") / 1048576 ))
  vg_mib=$(( disk_mib - BOOT_SIZE_MIB - 16 ))
  avail_mib=$(( vg_mib * 90 / 100 ))
  default_data_mib=$(( avail_mib * 30 / 100 ))

  # ---- 1. Size ----
  while :; do
    size_in=$(dlg_input_nav "Data volume size" \
"\n  How large should the data volume be?

  Available for root + data:  ${avail_mib} MiB
  (10% of the volume group is reserved for snapshots.)

  If data takes ${default_data_mib} MiB, root gets
  approximately $(( avail_mib - default_data_mib )) MiB.

  Enter size in MiB." \
      "$default_data_mib")
    rc=$?
    [ $rc -eq 0 ] || return 3
    size_in=$(_sanitize "$size_in")
    if ! [[ "$size_in" =~ ^[0-9]+$ ]]; then
      dlg_error "Enter a whole number of MiB."
      continue
    fi
    if [ "$size_in" -lt 256 ]; then
      dlg_error "Minimum 256 MiB."
      continue
    fi
    if [ "$size_in" -gt $(( avail_mib - 1024 )) ]; then
      dlg_error "Too large; root needs at least 1024 MiB."
      continue
    fi
    LVM_DATA_SIZE_MIB="$size_in"
    break
  done

  # ---- 2. Mount point ----
  while :; do
    local mnt
    mnt=$(dlg_input_nav "Data volume mount point" \
"\n  Where should the data volume be mounted?

  Absolute path. Examples:

    /data              a dedicated data area
    /srv/app           a specific application's storage
    /var/lib/mysql     a database directory
    /home              a separate home filesystem

  The directory will be created on the target and the data
  volume mounted there on every boot." \
      "/data")
    rc=$?
    [ $rc -eq 0 ] || return 3
    mnt=$(_sanitize "$mnt")

    case "$mnt" in
      "") dlg_error "Cannot be empty."; continue ;;
      /)  dlg_error "Cannot be the root filesystem."; continue ;;
      /boot|/boot/*) dlg_error "Cannot be under /boot."; continue ;;
    esac
    case "$mnt" in /*) ;; *) dlg_error "Must be an absolute path."; continue ;; esac
    case "$mnt" in *' '*) dlg_error "No spaces allowed."; continue ;; esac
    case "$mnt" in */..*|*/../*) dlg_error "No '..' allowed."; continue ;; esac

    LVM_DATA_MOUNT="$mnt"
    break
  done

  log "LVM data volume: yes, ${LVM_DATA_SIZE_MIB}MiB at $LVM_DATA_MOUNT"
  return 0
}

ui_hostname() {
  local h rc
  while :; do
    h=$(dlg_input_nav "Hostname" "\n  Enter the hostname for this machine." "amos")
    rc=$?
    case $rc in
      0) : ;;
      *) return 3 ;;
    esac
    h=$(_sanitize "$h")
    [ -n "$h" ] || { dlg_error "Cannot be empty."; continue; }
    [[ "$h" =~ ^[a-zA-Z0-9][a-zA-Z0-9-]*$ ]] || { dlg_error "Letters, digits, hyphens; start with letter or digit."; continue; }
    TARGET_HOSTNAME="$h"; return 0
  done
}

ui_user_account() {
  # Outer loop: Back from any sub-prompt returns to the yes/no so the
  # user can change their answer without skipping the whole step.
  local rc u
  while :; do
    dlg_yesno_nav "User account" "\n  Create a non-root user account?"
    rc=$?
    case $rc in
      0) : ;;
      1) USER_NAME=""; return 0 ;;
      *) return 3 ;;
    esac

    u=""
    while :; do
      u=$(dlg_input_nav "Username" "\n  Enter the username." "user")
      rc=$?
      case $rc in
        0) : ;;
        *) break ;;
      esac
      u=$(_sanitize "$u")
      [ -n "$u" ] || { dlg_error "Cannot be empty."; continue; }
      [[ "$u" =~ ^[a-z][a-z0-9_-]*$ ]] || { dlg_error "Start with lowercase letter."; continue; }
      break
    done
    [ -n "$u" ] || continue     # Back from username; re-ask yes/no

    USER_NAME="$u"
    if prompt_user_password; then
      return 0
    fi
    USER_NAME=""
    # Back from password prompt; re-ask yes/no
  done
}

ui_network() {
  local iface="" detected_ip="" detected_gw="" has_net=0
  local rc ui_ip ui_gw ui_dns

  # 1. Default interface. Prefer the interface carrying the default
  #    route; fall back to the first non-loopback if there is none.
  iface=$(ip -4 route show default 2>/dev/null \
          | awk '$2=="via" {print $5; exit}')
  if [ -z "$iface" ]; then
    iface=$(ls /sys/class/net 2>/dev/null | grep -v '^lo$' | head -n1)
  fi

  # 2. Default gateway on that interface. Filtering is done in awk
  #    because iproute2 drops the `dev <name>` token from output when
  #    the query already filters by dev. Regex uses explicit
  #    repetition, not {n}: mawk 1.3.4 and some busybox awk builds
  #    silently ignore interval expressions.
  if [ -n "$iface" ]; then
    detected_gw=$(ip -4 route show default 2>/dev/null \
                  | awk -v d="$iface" '
                      $1=="default" && $2=="via" \
                      && $3 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {
                        for (i=4; i<NF; i++)
                          if ($i=="dev" && $(i+1)==d) { print $3; exit }
                      }')

    # 3. IPv4 on that interface (global scope only). If several exist,
    #    prefer the one the kernel would use to reach the gateway.
    #    Falls back to the first global IP.
    if [ -n "$detected_gw" ]; then
      local src_ip
      src_ip=$(ip -4 route get "$detected_gw" 2>/dev/null \
               | awk '{for (i=1; i<NF; i++) if ($i=="src") {print $(i+1); exit}}')
      if [ -n "$src_ip" ]; then
        detected_ip=$(ip -4 -o addr show dev "$iface" scope global 2>/dev/null \
                      | awk -v s="$src_ip" '
                          { for (i=1; i<=NF; i++)
                              if ($i=="inet" && index($(i+1), s"/")==1) {
                                print $(i+1); exit
                              } }')
      fi
    fi
    [ -n "$detected_ip" ] || detected_ip=$(ip -4 -o addr show dev "$iface" scope global 2>/dev/null \
                                           | awk 'NR==1 {print $4}')

    # 4. Validate: shape/range first, then ask the kernel to confirm
    #    that (a) it would egress via $iface to reach $detected_gw and
    #    (b) the source it would use is exactly the IP we captured.
    #    A plausible-but-wrong pairing (multi-NIC, veth shadowing the
    #    real uplink) fails this check even though each value alone
    #    looks valid.
    if _valid_ipv4 "$detected_ip" && _valid_gateway "$detected_gw"; then
      local bare_ip="${detected_ip%/*}" mask="${detected_ip##*/}"
      case "$mask" in ''|*[!0-9]*) mask=0 ;; esac
      if [ "$mask" -ge 1 ] && [ "$mask" -le 32 ]; then
        local route_out
        route_out=$(ip -4 route get "$detected_gw" 2>/dev/null)
        if printf '%s\n' "$route_out" | grep -Fqw "dev $iface" \
           && printf '%s\n' "$route_out" | grep -Fqw "src $bare_ip"; then
          has_net=1
        else
          log "Network: kernel disagrees (ip=$detected_ip gw=$detected_gw iface=$iface route='${route_out:-<none>}')"
        fi
      fi
    else
      log "Network: shape/range rejected (ip=$detected_ip gw=$detected_gw)"
    fi

    # 5. Do not prefill the fallback prompt with garbage. Plausible
    #    values survive so the user can correct instead of retype;
    #    anything that failed shape/range is blanked.
    _valid_ipv4    "$detected_ip" || detected_ip=""
    _valid_gateway "$detected_gw" || detected_gw=""
  fi

  if [ "$MODE" = "quick" ]; then
    NETWORK_IFACE="$iface"

    if [ "$SLIRP" = "yes" ]; then
      NETWORK_MODE="dhcp"
      log "Quick mode: slirp NAT, DHCP on $iface ($detected_ip)"
      return 0
    fi

    if detect_dhcp "$iface"; then
      NETWORK_MODE="dhcp"
      NETWORK_IP="$detected_ip"
      NETWORK_GATEWAY="$detected_gw"
      log "Quick mode: DHCP on $iface ($detected_ip, gw $detected_gw)"
      return 0
    fi

    if [ "$has_net" -eq 1 ]; then
      dlg_yesno_nav "Network" \
"\n  Detected network configuration:

    IP       $detected_ip
    Gateway  $detected_gw
    Iface    $iface

  Use this configuration?" 
      rc=$?
      case $rc in
        0)
            NETWORK_MODE="static"
            NETWORK_IP="$detected_ip"
            NETWORK_GATEWAY="$detected_gw"
            log "Quick mode: static $iface ($detected_ip via $detected_gw) [confirmed]"
            return 0
            ;;
        1)
            log "Quick mode: user rejected detected values; prompting"
            ;;
        *)
            return 3
            ;;
      esac
    else
      log "Quick mode: auto-detection incomplete (ip=${detected_ip:-none} gw=${detected_gw:-none}); prompting"
    fi
  else
    if [ "$has_net" -eq 1 ]; then
      dlg_yesno_nav "Network Detected" \
"\n  The live environment has a working network on $iface.

  IP:       $detected_ip
  Gateway:  ${detected_gw:-none}

  Do you want to keep this configuration (DHCP), or
  configure a static IP?"
      rc=$?
      case $rc in
        0) NETWORK_MODE="dhcp"
           NETWORK_IFACE="$iface"
           return 0 ;;
        1) : ;;
        *) return 3 ;;
      esac
    else
      dlg_msg "DHCP Failed" "Automatic network configuration (DHCP) failed.\n\nPlease configure a static IP."
    fi
  fi

  # Static prompt — UNCHANGED (this is also the quick-mode fallback)
  while :; do
    ui_ip=$(dlg_input_nav "Static IP Address" \
      "\n  Enter IP address in CIDR notation (e.g., 123.123.123.12/27).
\n  Detected: ${detected_ip:-none}" \
      "${detected_ip:-}")
    rc=$?
    [ $rc -eq 0 ] || return 3
    ui_ip=$(_sanitize "$ui_ip")
    if [ -z "$ui_ip" ] || [[ "$ui_ip" != */* ]]; then
      dlg_error "Invalid format. Must include CIDR prefix (e.g., 10.0.0.5/24)."
      continue
    fi
    break
  done

  while :; do
    ui_gw=$(dlg_input_nav "Default Gateway" \
      "\n  Enter the default gateway IP address.
\n  Detected: ${detected_gw:-none}" \
      "${detected_gw:-}")
    rc=$?
    [ $rc -eq 0 ] || return 3
    ui_gw=$(_sanitize "$ui_gw")
    if [ -z "$ui_gw" ]; then
      dlg_error "Gateway cannot be empty."
      continue
    fi
    break
  done

  ui_dns=$(dlg_input_nav "DNS Servers" \
    "\n  Space-separated DNS addresses (e.g., 1.1.1.1 9.9.9.9)." \
    "1.1.1.1 9.9.9.9")
  rc=$?
  [ $rc -eq 0 ] || return 3
  ui_dns=$(_sanitize "$ui_dns")

  NETWORK_MODE="static"
  NETWORK_IFACE="$iface"
  NETWORK_IP="$ui_ip"
  NETWORK_GATEWAY="$ui_gw"
  NETWORK_DNS="$ui_dns"

  log "Network: static on $iface ($ui_ip via $ui_gw)"
  return 0
}

ui_ssh() {
  # Outer loop: Back from any sub-prompt returns to the yes/no so the
  # user can flip the enable/disable choice without skipping the step.
  local from port rc
  local default_from="${SSH_ALLOW_FROM:-10.0.2.2/32}"
  if [ -n "${SSH_CONNECTION:-}" ] && \
     { [ -z "${SSH_ALLOW_FROM:-}" ] || [ "$SSH_ALLOW_FROM" = "10.0.2.2/32" ]; }; then
    local ssh_client="${SSH_CONNECTION%% *}"
    [ -n "$ssh_client" ] && default_from="${ssh_client}/32"
    log "SSH allowlist prefill from SSH_CONNECTION: $default_from"
  fi
  while :; do
    dlg_yesno_nav "SSH server" "\n  Enable the OpenSSH server on this machine?"
    rc=$?
    case $rc in
      0) SSH_ENABLE="yes" ;;
      1) SSH_ENABLE="no"; return 0 ;;
      *) return 3 ;;
    esac

    from=$(dlg_input_nav "SSH allowed source" \
      "\n  Source range permitted to connect.\n  Examples:\n    10.0.2.2/32     single host\n    192.168.1.0/24  local network" \
      "$default_from")
    rc=$?
    case $rc in
      0) from=$(_sanitize "$from")
         SSH_ALLOW_FROM="${from:-10.0.2.2/32}" ;;
      *) continue ;;
    esac

    port=$(dlg_input_nav "SSH port" \
"\n  TCP port for sshd to listen on.

  Default is 62222.

  Port 22 is scanned by every automated SSH scanner on the
  internet. On a host with a public address that means thousands of
  failed-auth attempts per day in the auth log, and a standing
  position on the lists that automated tooling runs against
  whatever OpenSSH CVE is current." \
      "${SSH_PORT:-62222}")
    rc=$?
    case $rc in
      0) port=$(_sanitize "$port")
         case "$port" in
           ''|*[!0-9]*) dlg_error "Not a number."; continue ;;
         esac
         if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
           dlg_error "Port must be 1-65535."; continue
         fi
         SSH_PORT="$port" ;;
      *) continue ;;
    esac

    log "SSH from $SSH_ALLOW_FROM on port $SSH_PORT"
    return 0
  done
}

ui_timezone() {
  local zone_root="/usr/share/zoneinfo"
  local ztab="$zone_root/zone1970.tab"

  if [ ! -r "$ztab" ]; then
    warn "zone1970.tab not found; offering UTC only"
    TIMEZONE="UTC"
    return 0
  fi

  # Pinned entries: the most common zones, listed first for the
  # user who just wants to pick and move on.
  local -a pinned=(
    "UTC"                  "Coordinated Universal Time"
    "Europe/London"        "London, Dublin, Lisbon"
    "Europe/Paris"         "Paris, Berlin, Madrid, Rome, Amsterdam, Zurich, Vienna, Warsaw, Prague, Stockholm"
    "Europe/Helsinki"      "Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius"
    "Europe/Moscow"        "Moscow, Istanbul, Minsk"
    "America/New_York"     "Eastern Time (US/Canada)"
    "America/Chicago"      "Central Time (US/Canada)"
    "America/Denver"       "Mountain Time (US/Canada)"
    "America/Los_Angeles"  "Pacific Time (US/Canada)"
    "America/Sao_Paulo"    "São Paulo, Rio, Buenos Aires"
    "Africa/Johannesburg"  "Johannesburg, Cape Town"
    "Africa/Lagos"         "Lagos, Nairobi, Cairo, Casablanca"
    "Asia/Dubai"           "Dubai, Abu Dhabi, Muscat"
    "Asia/Kolkata"         "Kolkata, Mumbai, Delhi, Colombo"
    "Asia/Singapore"       "Singapore, Kuala Lumpur, Manila, Hong Kong"
    "Asia/Shanghai"        "Beijing, Shanghai, Taipei"
    "Asia/Tokyo"           "Tokyo, Osaka, Seoul"
    "Australia/Sydney"     "Sydney, Melbourne, Brisbane"
    "Pacific/Auckland"     "Auckland, Wellington, Fiji"
  )

  # Collect pinned names for the exclusion check.
  local -a pinned_names=()
  local p
  for p in "${pinned[@]}"; do
    case "$p" in
      *' '*) : ;;           # description, skip
      *) pinned_names+=("$p") ;;
    esac
  done
  local pinned_str=" ${pinned_names[*]} "

  local -a entries=()
  entries+=("${pinned[@]}")

  # Everything else from zone1970.tab, alphabetically, minus pins.
  # Format of zone1970.tab: country_codes<TAB>coordinates<TAB>zone_name
  local zone
  while IFS=$'\t' read -r cc coord zone; do
    [ -n "$zone" ] || continue
    case "$zone" in \#*) continue ;; esac
    case "$pinned_str" in
      *" $zone "*) continue ;;
    esac
  entries+=("$zone" "")
  done < "$ztab"

  local n_items=$(( ${#entries[@]} / 2 ))
  log "Timezone menu: $n_items items (${#pinned_names[@]} pinned)"

  local choice rc
  choice=$(dlg_menu_nav "Timezone" \
    "\n  Select the system timezone.\n\n  The most common timezones are listed first.\n  Everything else follows alphabetically by region.\n  Type the first letters of a region to jump to it.\n" \
    24 72 18 "${entries[@]}")
  rc=$?
  case $rc in
    0) choice=$(_sanitize "$choice")
       TIMEZONE="${choice:-UTC}"
       log "Timezone: $TIMEZONE"
       return 0 ;;
    *) return 3 ;;
  esac
}

ui_encryption_notice() {
  # Only ever added to the step list when ENCRYPT=yes (see _build_steps).
  local rc
  dlg_yesno_nav "Encryption: Please read" \
"You chose to encrypt the root filesystem.

  * Cipher: LUKS2 with AES-XTS (aes-xts-plain64) and a 512-bit key.
    This is the NIST standard for full-disk encryption and the
    default in every modern Linux distribution. It provides
    confidentiality, not integrity, for everything written to
    the disk.

  * Acceleration: AES-XTS is hardware-accelerated by AES-NI on any
    modern x86 CPU. Your encrypted disk will run at full speed.

  * Boot: You will be asked for your passphrase every time the
    system starts. Losing the passphrase means losing the data;
    there is no recovery key unless you make one yourself.

Continue with the encrypted install?"
  rc=$?
  case $rc in
    0) log "User confirmed encryption notice."; return 0 ;;
    *) return 3 ;;
  esac
}

ui_summary() {
  local enc="plain"
  [ "$ENCRYPT" = "yes" ] && enc="LUKS-encrypted"
  [ "$ENCRYPT" = "yes" ] && [ "$ENCRYPT_INTEGRITY" = "yes" ] && enc="LUKS-encrypted + integrity"

  local lvm_txt=""
  if [ "$USE_LVM" = "yes" ]; then
    lvm_txt=", LVM"
    if [ "$LVM_DATA_ENABLE" = "yes" ]; then
      lvm_txt="$lvm_txt (data LV: ${LVM_DATA_SIZE_MIB} MiB at $LVM_DATA_MOUNT)"
    fi
  fi
  local pass_txt="root only"
  [ -n "$USER_NAME" ] && pass_txt="root + $USER_NAME"
  local net_txt="DHCP"
  [ "$NETWORK_MODE" = "static" ] && net_txt="$NETWORK_IP"

  local text rc
  text=$(cat <<EOF

  Install summary
  ================================================

  Mode             $MODE
  Target disk      $TARGET_DISK
  Boot mode        $BOOTMODE
  Filesystem       $FSTYPE$lvm_txt, $enc
  Hostname         $TARGET_HOSTNAME
  Accounts         $pass_txt
  Network          $net_txt on ${NETWORK_IFACE:-auto}
  SSH              $SSH_ENABLE (from $SSH_ALLOW_FROM)
  Timezone         $TIMEZONE
  Keyboard         $KEYMAP

  ================================================
  All data on $TARGET_DISK will be erased.
EOF
)
  dlg_yesno_nav "Confirm installation" "$text"
  rc=$?
  case $rc in
    0) return 0 ;;
    1) dlg_msg "Cancelled" "Nothing has been changed."; exit 0 ;;
    *) return 3 ;;
  esac
}

ui_manual_devices() {
  # Step 1: prep notice as a proper Back-able dialog, replacing the
  # silent ui_manual_prep which could trap backward navigation.
  local rc choice dev fstype size label
  dlg_yesno_nav "Manual partitioning" \
"\n  Continue to a shell for manual partitioning?

  Create and format the partitions you want, then exit the
  shell to return.

  Required:
    root filesystem
    EFI System Partition (UEFI installs only)

  Optional:
    separate /boot
    swap partition  (a swapfile is used otherwise)

  Tools available:  cfdisk  fdisk  parted
                    mkfs.ext4  mkfs.xfs  mkfs.btrfs
                    mkfs.vfat  mkswap  cryptsetup
                    pvcreate  vgcreate  lvcreate"
  rc=$?
  case $rc in
    0) : ;;
    *) return 3 ;;
  esac

  # Step 2: drop to shell. Clear the dialog frame first so the shell
  # prompt is not drawn on top of the leftover box; clear again after
  # the shell exits so the next wizard dialog starts on blank screen.
  clear > /dev/tty 2>/dev/null || printf '\033[2J\033[H' > /dev/tty
  echo
  echo "  Dropping to a shell for manual partitioning."
  echo "  Type 'exit' when done."
  echo
  bash -l < /dev/tty > /dev/tty 2>&1 || true
  echo
  echo "  Returned to the installer wizard."
  clear > /dev/tty 2>/dev/null || printf '\033[2J\033[H' > /dev/tty

  # Step 3: pick the root device.
  local -a candidates=()
  while IFS= read -r dev; do
    [ -b "$dev" ] || continue
    case "$dev" in
      /dev/sr*|/dev/loop*|/dev/ram*|/dev/zram*) continue ;;
    esac
    fstype=$(blkid -s TYPE -o value "$dev" 2>/dev/null) || fstype=""
    [ -n "$fstype" ] || continue
    case "$fstype" in
       swap|crypto_*|*_member|bcache|drbd) continue ;;
    esac
    size=$(lsblk -nro SIZE "$dev" 2>/dev/null || echo "?")
    label=$(blkid -s LABEL -o value "$dev" 2>/dev/null || true)
    candidates+=("$dev" "$fstype  $size  ${label:-}")
  done < <(
    lsblk -pnro NAME,TYPE 2>/dev/null | awk '$2=="part"{print $1}'
    lsblk -pnro NAME,TYPE 2>/dev/null | awk '$2=="lvm"{print $1}'
    lsblk -pnro NAME,TYPE 2>/dev/null | awk '$2=="crypt"{print $1}'
  )

  if [ ${#candidates[@]} -eq 0 ]; then
    dlg_error "No formatted partitions found. Did you run mkfs?"
    return 3
  fi

  choice=$(dlg_menu_nav "Root device" \
    "\n  Select the device that will hold the root filesystem.\n  It must already be formatted.\n" \
    22 78 12 "${candidates[@]}")
  rc=$?
  case $rc in
    0) [ -n "$choice" ] || { dlg_error "Cancelled."; return 3; } ;;
    *) return 3 ;;
  esac
  MANUAL_ROOT="$choice"
  FSTYPE=$(blkid -s TYPE -o value "$MANUAL_ROOT")
  case "$FSTYPE" in
    swap|crypto_*|*_member|bcache|drbd)
      dlg_error "$MANUAL_ROOT is not a filesystem (blkid type: $FSTYPE).

  Select a device that has already been formatted with a
  filesystem such as ext4, xfs, or btrfs."
      return 3
      ;;
  esac
  log "Manual root: $MANUAL_ROOT ($FSTYPE)"

  # Build the ancestry chain from the root device up to the physical
  # disk using sysfs. util-linux 2.42's per-device lsblk invocations
  # (`lsblk -no PKNAME <dev>`, `lsblk -no TYPE <dev>`) return empty
  # for device-mapper nodes, and the inverse-tree form has been
  # inconsistent. sysfs exposes the parent relationships reliably:
  #
  #   - device-mapper nodes: /sys/class/block/<kname>/slaves/
  #     contains one symlink per parent device
  #   - partitions: parent is the enclosing disk, found via the
  #     resolved sysfs path
  #
  # /dev/mapper/cryptroot has kernel name dm-0, not cryptroot, so we
  # translate through `lsblk -no KNAME` first.
  local -a chain=()
  local cur="$MANUAL_ROOT"
  local kname parent real candidate parent_dir s
  while :; do
    chain+=("$cur")

    kname=$(lsblk -no KNAME "$cur" 2>/dev/null | head -1)
    [ -n "$kname" ] || break

    parent=""
    for s in /sys/class/block/"$kname"/slaves/*; do
      [ -e "$s" ] || continue
      parent=$(basename "$s")
      break
    done

    if [ -z "$parent" ]; then
      real=$(readlink -f "/sys/class/block/$kname" 2>/dev/null || true)
      if [ -n "$real" ]; then
        parent_dir=$(dirname "$real")
        # A whole disk resolves to .../block/<name>; its parent
        # directory is literally named "block", which is not a fdevice.
        # Partitions resolve to .../block/<disk>/<part>; their parent
        # directory basename is the enclosing disk.
        if [ "$(basename "$parent_dir")" != "block" ]; then
          candidate=$(basename "$parent_dir")
          [ "$candidate" != "$kname" ] && parent="$candidate"
        fi
      fi
    fi

    [ -n "$parent" ] || break
    cur="/dev/$parent"
  done

  # Fall back to just the root device if the walk produced nothing
  # usable.
  [ ${#chain[@]} -gt 0 ] || chain=("$MANUAL_ROOT")

  log "Manual ancestry chain: ${chain[*]}"

  MANUAL_LUKS_NAME=""
  MANUAL_CRYPT_PART=""
  VG_NAME=""
  LV_NAME=""
  local any_luks=0 any_lvm=0

  local i n d t kn dm_uuid
  n=${#chain[@]}
  for ((i=0; i<n; i++)); do
    d="${chain[$i]}"
    kn=$(lsblk -no KNAME "$d" 2>/dev/null | head -1)
    if [ -r "/sys/class/block/$kn/dm/uuid" ]; then
      dm_uuid=$(cat "/sys/class/block/$kn/dm/uuid")
      case "$dm_uuid" in
        CRYPT-*) t=crypt ;;
        LVM-*)   t=lvm   ;;
        *)       t=other ;;
      esac
    else
      t=$(lsblk -nro TYPE "$d" 2>/dev/null)
    fi
    case "$t" in
      crypt)
        any_luks=1
        [ -z "$MANUAL_LUKS_NAME" ] && MANUAL_LUKS_NAME=$(basename "$d")
        [ "$i" -lt $((n - 1)) ] && MANUAL_CRYPT_PART="${chain[$((i+1))]}"
        ;;
      lvm)
        any_lvm=1
        if [ -z "$VG_NAME" ]; then
          VG_NAME=$(lvs --noheadings -o vg_name "$d" 2>/dev/null | tr -d ' ')
          LV_NAME=$(lvs --noheadings -o lv_name "$d" 2>/dev/null | tr -d ' ')
        fi
        ;;
    esac
  done

  [ "$any_luks" = "1" ] && ENCRYPT="yes" || ENCRYPT="no"
  [ "$any_lvm"  = "1" ] && USE_LVM="yes" || USE_LVM="no"

  # Detect dm-integrity from the LUKS2 header. The user may have
  # formatted the container with --integrity; if so, the boot initrd
  # needs dm-integrity.ko and dm-bufio.ko to bring it up, and
  # exec_initrd() adds those modules only when ENCRYPT_INTEGRITY=yes.
  #
  # cryptsetup luksDump prints an "integrity:" key under the Data
  # segments section when the LUKS2 header carries an integrity
  # profile. Absence of that line means a plain dm-crypt container.
  ENCRYPT_INTEGRITY="no"
  if [ "$ENCRYPT" = "yes" ] && [ -n "$MANUAL_CRYPT_PART" ]; then
    if cryptsetup luksDump "$MANUAL_CRYPT_PART" 2>/dev/null \
         | grep -qE '^[[:space:]]*integrity:'; then
      ENCRYPT_INTEGRITY="yes"
      log "Manual LUKS: integrity detected in header"
    fi
  fi

  log "Manual stack:"
  log "  ENCRYPT=$ENCRYPT LUKS_NAME=$MANUAL_LUKS_NAME LUKS_PART=$MANUAL_CRYPT_PART"
  log "  USE_LVM=$USE_LVM VG=$VG_NAME LV=$LV_NAME"

  # In manual mode, the user prepares the storage in a shell before
  # returning to the wizard. For LUKS, that means they have already
  # opened the container with `cryptsetup open`. The mapper exists at
  # the path they selected, and there is nothing to open here.
  #
  # The check below only fires if the mapper somehow does not exist,
  # which cannot happen through the normal menu path (crypto_LUKS
  # devices are filtered out of the menu, so only already-open mappers
  # are selectable). It is present for defensiveness: if the mapper is
  # gone, prompt for the passphrase and open the underlying device
  # before proceeding.
  if [ "$ENCRYPT" = "yes" ] && [ ! -e "$MANUAL_ROOT" ]; then
    prompt_luks_passphrase || return 3
    if ! printf '%s' "$LUKS_PASSPHRASE" | \
         cryptsetup open --key-file - "$MANUAL_CRYPT_PART" "$LUKS_NAME" 2>/dev/null; then
      dlg_error "Failed to open $MANUAL_CRYPT_PART as $LUKS_NAME.

  The mapper was not present and the passphrase did not unlock
  the container. Check the device and try again."
      return 3
    fi
  fi

  LUKS_NAME="$MANUAL_LUKS_NAME"
  LUKS_PART="$MANUAL_CRYPT_PART"
  # Override with mkinitrd's convention so the boot init unlocks and
  # mounts the same mapper name.
  if [ -n "$MANUAL_CRYPT_PART" ]; then
    LUKS_NAME="luks$(basename "$MANUAL_CRYPT_PART")"
  fi

  # BIOS + LUKS or LVM needs a separate plain /boot partition: LILO
  # reads the kernel via BIOS int 13h and cannot see through LUKS or
  # LVM. Scan for a plain ext4 partition that is not the crypt
  # container and ask the user to confirm it as /boot.
  MANUAL_BOOT=""
  if [ "$BOOTMODE" = "bios" ] && \
     { [ "$ENCRYPT" = "yes" ] || [ "$USE_LVM" = "yes" ]; }; then
    local -a boots=()
    while IFS= read -r dev; do
      [ -b "$dev" ] || continue
      case "$dev" in /dev/sr*|/dev/loop*) continue ;; esac
      # Skip the crypt container itself.
      [ "$dev" = "$MANUAL_CRYPT_PART" ] && continue
      local bfstype
      bfstype=$(blkid -s TYPE -o value "$dev" 2>/dev/null || true)
      [ "$bfstype" = "ext4" ] || continue
      local bsize
      bsize=$(lsblk -nro SIZE "$dev" 2>/dev/null || echo "?")
      boots+=("$dev" "ext4  $bsize")
    done < <(lsblk -pnro NAME,TYPE 2>/dev/null | awk '$2=="part"{print $1}')

    if [ ${#boots[@]} -eq 0 ]; then
      dlg_error "BIOS + LUKS/LVM requires a separate plain ext4 /boot partition.

  LILO reads the kernel via BIOS int 13h and cannot see through an
  encrypted or LVM-mapped partition. Prepare a small ext4 partition
  (1 GiB is ample) for /boot, then re-run setup."
      return 3
    fi

    local bchoice
    if [ ${#boots[@]} -eq 2 ]; then
      MANUAL_BOOT="${boots[0]}"
    else
      bchoice=$(dlg_menu_nav "Boot partition" \
        "\n  Select the plain ext4 partition to mount at /boot.

  LILO cannot read an encrypted or LVM-mapped /boot, so this must
  be a separate plain partition." \
        18 78 6 "${boots[@]}")
      rc=$?
      case $rc in
        0) [ -n "$bchoice" ] || { dlg_error "Cancelled."; return 3; } ;;
        *) return 3 ;;
      esac
      MANUAL_BOOT="$bchoice"
    fi
    log "Manual /boot: $MANUAL_BOOT"
  fi
  

  # The physical disk is the last element of the ancestry chain we
  # already built. Do not query lsblk again; its per-device PKNAME
  # form is unreliable on this util-linux version.
  local chain_len=${#chain[@]}
  local root_pk=""
  if [ "$chain_len" -gt 0 ]; then
    root_pk="${chain[$((chain_len - 1))]}"
  fi
  [ -n "$root_pk" ] || { dlg_error "Cannot determine the disk holding $MANUAL_ROOT."; return 3; }
  MANUAL_DISK="$root_pk"
  TARGET_DISK="$MANUAL_DISK"
  MANUAL_LAYOUT="yes"
  log "Manual disk: $MANUAL_DISK"

  MANUAL_ESP=""
  MANUAL_ESP_DISK=""
  MANUAL_ESP_PART=""
  if [ "$BOOTMODE" = "efi" ]; then
    local -a esps=()
    while IFS= read -r dev; do
      [ -b "$dev" ] || continue
      case "$dev" in /dev/sr*|/dev/loop*) continue ;; esac
      fstype=$(blkid -s TYPE -o value "$dev" 2>/dev/null || true)
      case "$fstype" in vfat|msdos) ;; *) continue ;; esac
      size=$(lsblk -nro SIZE "$dev" 2>/dev/null || echo "?")
      esps+=("$dev" "FAT32  $size")
    done < <(lsblk -pnro NAME,TYPE 2>/dev/null | awk '$2=="part"{print $1}')

    if [ ${#esps[@]} -eq 0 ]; then
      dlg_error "No FAT32 partition found.

  UEFI firmware requires the EFI System Partition to be
  formatted as FAT32. Create one, then re-run setup."
      return 3
    fi

    if [ ${#esps[@]} -eq 2 ]; then
      MANUAL_ESP="${esps[0]}"
    else
      choice=$(dlg_menu_nav "EFI System Partition" \
        "\n  Select the FAT32 partition to mount at /boot/efi.\n" \
        18 78 6 "${esps[@]}")
      rc=$?
      case $rc in
        0) [ -n "$choice" ] || { dlg_error "Cancelled."; return 3; } ;;
        *) return 3 ;;
      esac
      MANUAL_ESP="$choice"
    fi

    # Parent disk of the ESP: sysfs read of the resolved path, since
    # lsblk's per-device PKNAME form is unreliable on this util-linux.
    local esp_kname esp_real esp_parent
    esp_kname=$(basename "$MANUAL_ESP")
    esp_real=$(readlink -f "/sys/class/block/$esp_kname" 2>/dev/null || true)
    esp_parent=$(basename "$(dirname "$esp_real")" 2>/dev/null)
    if [ -z "$esp_parent" ] || [ "$esp_parent" = "$esp_kname" ]; then
      dlg_error "Cannot determine the ESP's parent disk."
      return 3
    fi
    MANUAL_ESP_DISK="/dev/$esp_parent"

    MANUAL_ESP_PART=$(cat "/sys/class/block/$esp_kname/partition" 2>/dev/null)
    [ -n "$MANUAL_ESP_PART" ] || { dlg_error "Cannot determine the ESP partition number."; return 3; }

    log "Manual ESP: $MANUAL_ESP (disk=$MANUAL_ESP_DISK part=$MANUAL_ESP_PART)"
  fi
  return 0
}

# ---------------------------------------------------------------------------
#  Wizard walker
# ---------------------------------------------------------------------------

_build_steps() {
  WIZ_STEPS=()
  WIZ_STEPS+=(ui_mode)
  WIZ_STEPS+=(ui_keymap)

  case "$MODE" in
    manual)
      WIZ_STEPS+=(ui_manual_devices)
      WIZ_STEPS+=(ui_hostname)
      WIZ_STEPS+=(prompt_root_password)
      WIZ_STEPS+=(ui_user_account)
      WIZ_STEPS+=(ui_network)
      WIZ_STEPS+=(ui_ssh)
      WIZ_STEPS+=(ui_timezone)
      [ "$ENCRYPT" = "yes" ] && WIZ_STEPS+=(ui_encryption_notice)
      ;;
    advanced)
      WIZ_STEPS+=(ui_disk)
      WIZ_STEPS+=(ui_fstype)
      WIZ_STEPS+=(ui_encryption)
      # Conditional steps are filtered here rather than executed as
      # no-ops. A silent step would trap backward navigation: Back
      # would land on a step that returns 0 immediately, advancing
      # the user right back to where they were.
      [ "$ENCRYPT" = "yes" ] && WIZ_STEPS+=(ui_encryption_integrity)
      WIZ_STEPS+=(ui_lvm)
      [ "$USE_LVM" = "yes" ] && WIZ_STEPS+=(ui_lvm_data)
      WIZ_STEPS+=(ui_hostname)
      WIZ_STEPS+=(prompt_root_password)
      WIZ_STEPS+=(ui_user_account)
      WIZ_STEPS+=(ui_network)
      WIZ_STEPS+=(ui_ssh)
      WIZ_STEPS+=(ui_timezone)
      [ "$ENCRYPT" = "yes" ] && WIZ_STEPS+=(ui_encryption_notice)
      ;;
    quick)
      WIZ_STEPS+=(ui_disk)
      WIZ_STEPS+=(prompt_root_password)
      WIZ_STEPS+=(ui_network)
      if [ "$SLIRP" = "yes" ]; then
        :                              # SSH auto-enabled inside ui_mode
      else
        WIZ_STEPS+=(ui_ssh)
      fi
      ;;
  esac
  WIZ_STEPS+=(ui_summary)
}

run_wizard() {
  local idx=0
  _build_steps

  while [ $idx -lt ${#WIZ_STEPS[@]} ]; do
    local fn="${WIZ_STEPS[$idx]}"
    local rc=0

    # set -e would exit the script on a Back (rc=3) since a bare
    # command returning non-zero is fatal. Suppress it around the
    # step invocation only.
    set +e
    "$fn"
    rc=$?
    set -e

    case $rc in
      0)
        # Rebuild the step list after every successful step: earlier
        # steps may have changed MODE (ui_mode) or ENCRYPT
        # (ui_encryption, ui_manual_devices), and the conditional
        # steps depend on both.
        idx=$((idx+1))
        _build_steps
        ;;
      3)
        if [ $idx -eq 0 ]; then
          if dlg_yesno_nav "Exit installer" \
"\n  You are on the first step. Pressing Back will exit the
  installer and no changes will be made.

  Exit now?"; then
            exit 0
          fi
          # User said No; stay on step 0.
        else
          idx=$((idx-1))
        fi
        ;;
      *)
        log "Wizard step $fn returned unexpected rc=$rc; aborting."
        exit 1
        ;;
    esac
  done
}

# ---------------------------------------------------------------------------
#  Config writing
# ---------------------------------------------------------------------------

write_config() {
  (
  umask 077
  {
    printf '# AM·OS installer configuration.\n'
    printf '# Generated by setup.sh at %s.\n' "$(date)"
    printf '# User secrets are NOT stored here. They are passed via the environment.\n'
    printf 'MODE=%q\n'              "$MODE"
    printf 'TARGET_DISK=%q\n'       "$TARGET_DISK"
    printf 'BOOTMODE=%q\n'          "$BOOTMODE"
    printf 'FSTYPE=%q\n'            "$FSTYPE"
    printf 'ENCRYPT=%q\n'           "$ENCRYPT"
    printf 'ENCRYPT_INTEGRITY=%q\n' "$ENCRYPT_INTEGRITY"
    printf 'USE_LVM=%q\n'           "$USE_LVM"
    printf 'TARGET_HOSTNAME=%q\n'   "$TARGET_HOSTNAME"
    printf 'USER_NAME=%q\n'         "$USER_NAME"
    printf 'SSH_ENABLE=%q\n'        "$SSH_ENABLE"
    printf 'SSH_ALLOW_FROM=%q\n'    "$SSH_ALLOW_FROM"
    printf 'NETWORK_MODE=%q\n'      "$NETWORK_MODE"
    printf 'NETWORK_IFACE=%q\n'     "$NETWORK_IFACE"
    printf 'NETWORK_IP=%q\n'        "$NETWORK_IP"
    printf 'NETWORK_GATEWAY=%q\n'   "$NETWORK_GATEWAY"
    printf 'NETWORK_DNS=%q\n'       "$NETWORK_DNS"
    printf 'SSH_PORT=%q\n' "$SSH_PORT"
    printf 'TIMEZONE=%q\n'          "$TIMEZONE"
    printf 'KEYMAP=%q\n'            "$KEYMAP"
    printf 'ISO_SRC=%q\n'           "$ISO_SRC"
    printf 'ESP_SIZE_MIB=%d\n'      "$ESP_SIZE_MIB"
    printf 'BOOT_SIZE_MIB=%d\n'     "$BOOT_SIZE_MIB"
    printf 'SWAP_SIZE_MIB=%d\n'     "$SWAP_SIZE_MIB"
    printf 'VIDEO_RES=%q\n'         "$VIDEO_RES"
    printf 'ZSWAP_MAX_POOL=%d\n'    "$ZSWAP_MAX_POOL"
    printf 'LUKS_NAME=%q\n'         "$LUKS_NAME"
    printf 'VG_NAME=%q\n'           "$VG_NAME"
    printf 'LV_NAME=%q\n'           "$LV_NAME"
    printf 'LVM_ROOT_PERCENT=%d\n'  "$LVM_ROOT_PERCENT"
    printf 'LVM_DATA_ENABLE=%q\n'   "$LVM_DATA_ENABLE"
    printf 'LVM_DATA_SIZE_MIB=%d\n' "$LVM_DATA_SIZE_MIB"
    printf 'LVM_DATA_NAME=%q\n'     "$LVM_DATA_NAME"
    printf 'LVM_DATA_MOUNT=%q\n'    "$LVM_DATA_MOUNT"
    printf 'MANUAL_LAYOUT=%q\n'     "${MANUAL_LAYOUT:-no}"
    printf 'MANUAL_ROOT=%q\n'       "${MANUAL_ROOT:-}"
    printf 'MANUAL_DISK=%q\n'       "${MANUAL_DISK:-}"
    printf 'MANUAL_ESP=%q\n'        "${MANUAL_ESP:-}"
    printf 'MANUAL_ESP_DISK=%q\n'   "${MANUAL_ESP_DISK:-}"
    printf 'MANUAL_ESP_PART=%q\n'   "${MANUAL_ESP_PART:-}"
    printf 'MANUAL_CRYPT_PART=%q\n' "${MANUAL_CRYPT_PART:-}"
    printf 'MANUAL_BOOT=%q\n'       "${MANUAL_BOOT:-}"
  } > "$CONFIG_FILE"
  )
  chmod 600 "$CONFIG_FILE" || true
  log "Config written to $CONFIG_FILE (no secrets)"
}

cleanup_stale_target() {
  local m cleaned=0
  for m in /target/mnt/iso /target/dev/pts /target/dev \
           /target/proc /target/sys \
           /target/boot/efi /target/boot /target; do
    mountpoint -q "$m" 2>/dev/null || continue
    umount -l "$m" 2>/dev/null && cleaned=1 || true
  done
  if [ "$cleaned" = "1" ]; then
    log "Cleaned up stale mounts under /target from a previous run."
  fi
}

main() {
  [ "$(id -u)" -eq 0 ] || { echo "Run as root." >&2; exit 1; }
  open_tty || { echo "No usable terminal." >&2; exit 1; }
  detect_environment
  cleanup_stale_target
  log "setup.sh started at $(date)"

  detect_bootmode
  detect_iso_source || { dlg_error "Cannot locate installation media."; exit 1; }

  dlg_msg "Welcome" \
"Welcome to the AM·OS installer.

You are about to install a fresh AM·OS system.

You will be asked a few questions about the target disk,
security, and networking. Once set, the installation itself
runs unattended and takes several minutes.

Use the Back button on any screen to return to the previous
question.

Proceed when you are ready."

  run_wizard

  write_config

  if dlg_yesno "Ready to install" \
"\n  Configuration saved.

  Begin installation now?"; then
    export ROOT_PASSWORD
    export USER_PASSWORD
    export LUKS_PASSPHRASE
    close_tty
    exec "$SCRIPT_DIR/install.sh"
  else
    dlg_msg "Saved" "Configuration saved to $CONFIG_FILE.

  Secrets were NOT saved. When you run install.sh later,
  it will ask for them again."
  fi
}

main "$@"