#!/usr/bin/env bash
# ============================================================================
# gentoo-install.sh — interactive two-stage Gentoo installer
#
#   Stage 1 (run from a live USB/CD environment, as root):
#       picks disk, layout, encryption, filesystems, swap, profile, mirrors,
#       CFLAGS/USE/video flags; partitions, unpacks stage3, sets up mounts,
#       then hands you into stage 2 inside the chroot.
#   Stage 2 (runs inside the chroot automatically, or resume manually with:
#       chroot /mnt/gentoo /bin/bash /root/gentoo-install.sh stage2 ):
#       timezone/locale/keymap, root password (YOU type it; never stored by
#       this script), kernel, bootloader, networking, world update,
#       desktop/browser/extras, user accounts, services.
#
#   Requires a stage3-capable live environment (the Gentoo livecd is perfect).
#   This script NEVER captures your password into a variable or file: it
#   execs `passwd` and lets you type it at the terminal prompt directly.
# ============================================================================

# Not using `set -e` on purpose: this is an interactive script and we handle
# errors per-step with explicit prompts instead of dying mid-partition.
set -o pipefail

GROOT=/mnt/gentoo
STATEFILE="$GROOT/root/gentoo-install.state"
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
VERSION="2026-11-14.2"

# ----------------------------- pretty output -------------------------------
if [ -t 1 ]; then
    B=$'\e[1;34m'; G=$'\e[1;32m'; R=$'\e[1;31m'; Y=$'\e[1;33m'; C=$'\e[1;36m'; D=$'\e[0;90m'; X=$'\e[0m'
else
    B=; G=; R=; Y=; C=; D=; X=
fi
say()  { printf '%b\n' "$*"; }
hr()   { say "${D}------------------------------------------------------------${X}"; }
step() { say "\n${C}>>> $*${X}"; hr; }
warn() { say "${Y}!! $*${X}"; }
die()  { say "${R}xx $*${X}"; exit 1; }
ok()   { say "${G}++ $*${X}"; }
esay() { printf '%b\n' "$*" >&2; }   # menu noise: stderr, so $(...) capture stays clean

# ------------------------------ menu helpers -------------------------------
# menu "Title" "item one" "item two" ... -> echoes chosen 1-based index
menu() {
    local title="$1"; shift
    local i=1 item a
    esay "\n${B}${title}${X}"
    for item in "$@"; do esay "  ${Y}$i)${X} $item"; i=$((i+1)); done
    while :; do
        printf '%b' "${C}pick [1-$#]: ${X}" >&2; read -r a
        case "$a" in ''|*[!0-9]*) esay "${Y}!! enter a number 1-$#${X}"; continue ;; esac
        if [ "$a" -ge 1 ] && [ "$a" -le $# ]; then printf '%s\n' "$a"; return 0; fi
        esay "${Y}!! enter a number 1-$#${X}"
    done
}
pick() {  # pick "Title" items... -> echoes chosen text (not index)
    local idx; idx=$(menu "$@")
    shift; shift $((idx - 1))   # drop title, then step to the chosen item
    printf '%s\n' "$1"
}
ask() {  # ask "Question" [default] -> echoes answer (prompt on stderr)
    local q="$1" def="${2:-}" a
    printf '%b' "${C}${q}${X}${def:+ ${D}[$def]${X}}: " >&2
    read -r a
    printf '%s\n' "${a:-$def}"
}
ask_required() {  # ask_required "Question" -> echoes non-empty answer
    local a
    while :; do
        a=$(ask "$1")
        [ -n "$a" ] && { printf '%s\n' "$a"; return 0; }
        esay "${Y}!! a value is required${X}"
    done
}
yesno() {  # yesno "Question" [Y|N] -> exit 0/1 (prompt on stderr)
    local a d="${2:-y}"
    while :; do
        printf '%b' "${C}${1}${X} ${D}(y/n)${X} " >&2
        read -r a
        case "$a" in
            [Yy]*) return 0 ;;
            [Nn]*) return 1 ;;
            '') [ "$d" = y ] && return 0 || return 1 ;;
            *) warn "y or n" ;;
        esac
    done
}
# multiselect "Title" item1 item2 ... -> echoes chosen labels, space separated
multiselect() {
    local title="$1"; shift
    local sel=() chosen=() item i a
    esay "\n${B}${title}${X}"
    esay "${D}(toggle numbers with spaces, e.g. '2 5 6'; empty line = done)${X}"
    i=1
    for item in "$@"; do sel[$i]="$item"; esay "  ${Y}$i)${X} $item"; i=$((i+1)); done
    local total=$((i-1))
    while :; do
        printf '%b' "${C}toggle/done: ${X}" >&2; read -ra a
        [ ${#a[@]} -eq 0 ] && break
        for n in "${a[@]}"; do
            case "$n" in
                *[!0-9]*) esay "${Y}!! numbers only${X}"; continue ;;
            esac
            if [ "$n" -ge 1 ] && [ "$n" -le "$total" ]; then
                if [[ " ${chosen[*]-} " == *" ${sel[$n]} "* ]]; then
                    chosen=("${chosen[@]/${sel[$n]}}")
                    esay "${D}  - removed: ${sel[$n]}${X}"
                else
                    chosen+=("${sel[$n]}")
                    esay "${G}  + added: ${sel[$n]}${X}"
                fi
            fi
        done
    done
    ( IFS=$'\n'; printf '%s\n' "${chosen[@]-}" ) | grep -v '^$' | paste -sd' ' -
}

# ===========================================================================
#                              STAGE 1
# ===========================================================================
stage1() {
    say "${B}"
    say "============================================================"
    say "  Gentoo installer - STAGE 1 (before chroot)  v$VERSION"
    say "  disk / filesystems / stage3 / make.conf / mounts"
    say "============================================================${X}"

    [ "$(id -u)" -eq 0 ] || die "stage 1 must run as root (from the live environment)"

    step "Pre-flight checks"
    local missing=()
    for c in parted mkfs partprobe tar wget blkid; do
        command -v "$c" >/dev/null || missing+=("$c")
    done
    [ ${#missing[@]} -eq 0 ] || die "missing tools: ${missing[*]} (run from the Gentoo livecd)"
    ARCH=$(uname -m)
    case "$ARCH" in
        x86_64)  ARCH=amd64 ;;
        aarch64) ARCH=arm64 ;;
        *) die "unsupported arch: $ARCH" ;;
    esac
    ok "arch: $ARCH"
    EFI=0; [ -d /sys/firmware/efi ] && EFI=1
    ok "boot mode: $([ $EFI = 1 ] && echo 'UEFI' || echo 'legacy BIOS')"
    if ! ping -c1 -W3 8.8.8.8 >/dev/null 2>&1 && ! wget -q -O- --timeout=8 https://www.gentoo.org >/dev/null 2>&1; then
        warn "internet does not look reachable; continuing, but downloads may fail"
    else
        ok "internet: reachable"
    fi
    YEAR=$(date +%Y); [ "$YEAR" -ge 2024 ] || warn "system clock year is $YEAR - fix it or portage will complain"
    yesno "Gentoo is about to DESTROY data on the disk you pick. Proceed?" y || die "aborted, nothing touched"

    # ------------------------------------------------------------- disk ----
    step "Target disk"
    say "Available disks:"
    lsblk -d -o NAME,SIZE,TYPE,MODEL,DISCGRP 2>/dev/null | sed 's/^/  /' || lsblk -d
    DISK_BASE=$(ask_required "Pick disk (basename, e.g. sda / nvme0n1)")
    DISK="/dev/$DISK_BASE"
    [ -b "$DISK" ] || die "no such block device: $DISK"
    say "${R}WARNING: everything on $DISK will be erased.${X}"
    say "Type ${R}${DISK_BASE}${X} to confirm: "
    read -r conf; [ "$conf" = "$DISK_BASE" ] || die "confirmation mismatch - aborting"

    step "Partition layout"
    if [ $EFI -eq 1 ]; then
        LAYOUT=$(pick "Layout (UEFI):" \
            "GPT: ESP 1G + swap + root (recommended)" \
            "GPT: ESP 1G + root only (swapfile later)" \
            "manual - I partition myself with cfdisk, you continue" )
    else
        LAYOUT=$(pick "Layout (BIOS/MBR):" \
            "MBR: root + swap (recommended)" \
            "MBR: root only" \
            "manual - I partition myself with cfdisk, you continue" )
    fi

    ENCRYPT=0; SWAP_GB=0; FS=ext4; SWAP_CHOICE=0
    case "$LAYOUT" in
        manual) warn "manual layout: you partition now, I take over after. Point the partitions yourself at the next prompts."
            cfdisk "$DISK"; partprobe "$DISK"
            ROOT_PART=$(ask_required "root partition (e.g. ${DISK}1)")
            [ -b "$ROOT_PART" ] || die "no such partition: $ROOT_PART"
            if yesno "is there a separate ESP partition? (UEFI only)" n; then
                ESP_PART=$(ask_required "ESP partition:"); [ -b "$ESP_PART" ] || die "no such partition"
            fi
            if yesno "is there a swap partition to activate? (format it too)" n; then
                SWAP_PART=$(ask_required "swap partition:"); [ -b "$SWAP_PART" ] || die "no such partition"
            fi
            ;;
        *)
            step "Encryption"
            if yesno "encrypt the root partition with LUKS?" n; then
                ENCRYPT=1
                warn "LUKS root forces the genkernel route in stage 2 (initramfs with cryptsetup)"
            fi
            step "Swap"
            SWAP_GB=$(pick "How much swap?" "none" "8 GB" "16 GB" "32 GB" "all the rest")
            case "$SWAP_GB" in
                none) SWAP_CHOICE=0 ;;
                "all the rest") SWAP_CHOICE=-1 ;;
                *) SWAP_GB=${SWAP_GB% GB}; SWAP_CHOICE=$SWAP_GB ;;
            esac
            step "Filesystem for /"
            FS=$(pick "Root filesystem:" "ext4 (rock solid)" "btrfs (snapshots/CoW)" "xfs" "f2fs (flash-friendly)")
            ;;
    esac

    # ---------------------------------------------------------- profile ----
    step "Profile + stage3 variant"
    PROFILE=$(pick "Portage profile (amd64 23.0):" \
        "default (no desktop, OpenRC)" \
        "desktop (OpenRC)" \
        "desktop/plasma (OpenRC)" \
        "desktop/plasma/systemd" \
        "desktop/gnome/systemd" \
        "desktop/gnome (OpenRC)" \
        "systemd (no desktop)" )
    case "$PROFILE" in
        "default")                  PROFILE="default/linux/$ARCH/23.0" ;;
        "desktop")                  PROFILE="default/linux/$ARCH/23.0/desktop" ;;
        "desktop/plasma (OpenRC)")  PROFILE="default/linux/$ARCH/23.0/desktop/plasma" ;;
        "desktop/plasma/systemd")   PROFILE="default/linux/$ARCH/23.0/desktop/plasma/systemd" ;;
        "desktop/gnome/systemd")    PROFILE="default/linux/$ARCH/23.0/desktop/gnome/systemd" ;;
        "desktop/gnome (OpenRC)")   PROFILE="default/linux/$ARCH/23.0/desktop/gnome" ;;
        "systemd (no desktop)")     PROFILE="default/linux/$ARCH/23.0/systemd" ;;
    esac
    case "$PROFILE" in
        */systemd*) INIT=systemd ;;
        *)          INIT=openrc ;;
    esac
    ok "profile: $PROFILE  (init: $INIT)"

    # ---------------------------------------------------------- network ----
    step "Mirrors + sync"
    MIRROR=$(pick "Gentoo mirror for stage3 download:" \
        "bouncer (auto-picks nearest, recommended)" \
        "eu: https://ftp.gentoo.mesh-solutions.com/gentoo" \
        "eu: https://mirror.leaseweb.com/gentoo" \
        "us: https://gentoo.mirrors.liquidweb.com" \
        "us: https://mirror.arizona.edu/gentoo-portage" \
        "asia: https://ftp.jaist.ac.jp/pub/Linux/Gentoo" \
        "custom URL next" )
    case "$MIRROR" in
        bouncer*) MIRROR="https://bouncer.gentoo.org/fetch/root/all" ;;
        "custom URL next") MIRROR=$(ask_required "mirror base URL (no trailing slash)") ;;
        *) MIRROR="${MIRROR##*: }" ;;
    esac
    SYNC=$(pick "Portage tree sync method:" \
        "rsync (default)" \
        "git (qq desktop-friendly clones)" \
        "emerge --webrsync (firewall-friendly, slowest)" )
    case "$SYNC" in
        rsync*) SYNC_URL="rsync://rsync.gentoo.org/gentoo-portage" ;;
        git*)   SYNC_URL="https://github.com/gentoo-mirror/gentoo.git" ;;
        *)      SYNC_URL="" ; warn "webrsync: SYNC line omitted; run 'emerge --webrsync' manually in stage 2" ;;
    esac

    step "Network for the install"
    WIFI_NEEDED=$(pick "How is the live environment connected?" "wired/USB-ethernet (already online)" "wifi (I'll configure it in stage 2)" "offline-ish, webrsync only")
    [ "$WIFI_NEEDED" = "wired/USB-ethernet (already online)" ] && HAS_WIFI=0 || HAS_WIFI=1

    # ------------------------------------------------------ compile flags --
    step "Compiler + USE + video"
    if yesno "use -march=native (recommended for this machine)?" y; then MARCH="-march=native"; else MARCH="-march=x86-64-v2"; fi
    OPT=$(pick "Optimization level:" "-O2 (recommended)" "-O3 (faster runtime, slower builds)" "-Os (small)")
    LTO=0
    if yesno "enable LTO (slower builds, needs care; expert)" n; then LTO=1; fi
    NPROC=$(nproc)
    MAKE_JOBS=$(ask "make -j (parallelism)" "$NPROC")
    CCACHE=$(yesno "ccache (speeds up rebuilds)?" y && echo 1 || echo 0)

    USE_LIST=$(multiselect "Extra USE flags:" \
        "pipewire (modern audio)" "bluetooth" "wayland" "wifi" "exfat" "ntfs-3g" \
        "zsh" "cryptsetup" "usb" "udisks")
    VIDEO=$(multiselect "Video cards (VIDEO_CARDS):" \
        "intel" "amdgpu" "nvidia" "nouveau" "modesetting (X generic)" \
        "vmware" "virtio_gpu" "vc4 (raspberry pi)" )

    HOSTNAME=$(ask "Hostname" "gentoo-box")

    # -------------------------------------------------------- partition ----
    step "Partitioning $DISK"
    partnum() { case "$DISK" in *nvme*|*mmcblk*) echo "${DISK}p$1" ;; *) echo "${DISK}$1" ;; esac; }
    if [ "$LAYOUT" != "manual" ]; then
        DISK_MB=$(( $(blockdev --getsz "$DISK") / 2048 ))
        SW_MB=$([ "$SWAP_CHOICE" = "-1" ] && echo 32768 || echo $((SWAP_CHOICE * 1024)))
        if [ $EFI = 1 ]; then NEEDED_MB=$((1025 + SW_MB)); else NEEDED_MB=$SW_MB; fi
        [ $NEEDED_MB -lt $((DISK_MB - 1024)) ] || die "disk is only $DISK_MB MiB - too small for ESP+${SW_MB} MiB swap plus a usable root; pick smaller swap"
        wipefs -a "$DISK" >/dev/null 2>&1
        if [ $EFI -eq 1 ]; then
            parted -s "$DISK" mklabel gpt
            parted -s "$DISK" mkpart esp fat32 1MiB 1025MiB
            parted -s "$DISK" set 1 esp on
            if [ "$SWAP_CHOICE" != "0" ] && [ "$SWAP_CHOICE" != "-1" ]; then
                parted -s "$DISK" mkpart swap 1025MiB $((1025 + SWAP_CHOICE * 1024))MiB
                parted -s "$DISK" mkpart root $((1025 + SWAP_CHOICE * 1024))MiB 100%
            elif [ "$SWAP_CHOICE" = "-1" ]; then
                warn "'all the rest' as swap leaves no root - using 32 GB swap instead"
                parted -s "$DISK" mkpart swap 1025MiB $((1025 + 32 * 1024))MiB
                parted -s "$DISK" mkpart root $((1025 + 32 * 1024))MiB 100%
            else
                parted -s "$DISK" mkpart root 1025MiB 100%
            fi
            ESP_PART=$(partnum 1); ROOT_PART=$(partnum "$([ "$SWAP_CHOICE" = "0" ] && echo 2 || echo 3)")
            [ "$SWAP_CHOICE" != "0" ] && SWAP_PART=$(partnum 2)
        else
            DISK_MB=$(( $(blockdev --getsz "$DISK") / 2048 ))
            SW_MB=$([ "$SWAP_CHOICE" = "-1" ] && echo 32768 || echo $((SWAP_CHOICE * 1024)))
            [ "$SWAP_CHOICE" = "-1" ] && warn "'all the rest' swap would leave no root - using 32 GB swap"
            parted -s "$DISK" mklabel msdos
            if [ "$SWAP_CHOICE" != "0" ]; then
                parted -s "$DISK" mkpart primary 1MiB $((DISK_MB - SW_MB))MiB
                parted -s "$DISK" mkpart primary $((DISK_MB - SW_MB))MiB 100%
                parted -s "$DISK" set 1 boot on
                ROOT_PART=$(partnum 1); SWAP_PART=$(partnum 2)
            else
                parted -s "$DISK" mkpart primary 1MiB 100%
                parted -s "$DISK" set 1 boot on
                ROOT_PART=$(partnum 1)
            fi
        fi
        partprobe "$DISK"; sleep 2
    fi
    ok "ESP=${ESP_PART:-none}  swap=${SWAP_PART:-none}  root=$ROOT_PART"

    # -------------------------------------------------------- encrypt ------
    if [ $ENCRYPT -eq 1 ]; then
        step "LUKS setup on $ROOT_PART"
        say "Type the disk-encryption key at cryptsetup's prompt (twice). This key is never stored."
        cryptsetup luksFormat -y --pbkdf argon2id --pbkdf-force-iterations 10000 "$ROOT_PART" || die "luksFormat failed"
        cryptsetup open "$ROOT_PART" groot || die "could not open mapped root"
        ROOT_TGT=/dev/mapper/groot
        ok "mapped $ROOT_PART -> $ROOT_TGT"
    else
        ROOT_TGT="$ROOT_PART"
    fi

    # ---------------------------------------------------------- format -----
    step "Formatting"
    if [ -n "${ESP_PART:-}" ]; then
        mkfs.vfat -F32 "$ESP_PART" >/dev/null && ok "ESP fat32: $ESP_PART" || die "mkfs.vfat failed"
    fi
    [ -n "${SWAP_PART:-}" ] && mkswap "$SWAP_PART" >/dev/null && ok "swap: $SWAP_PART"
    case "$FS" in
        ext4)  mkfs.ext4 -q -L gentoo "$ROOT_TGT" ;;
        btrfs) command -v mkfs.btrfs >/dev/null || die "mkfs.btrfs missing in live env"; mkfs.btrfs -f -L gentoo "$ROOT_TGT" ;;
        xfs)   mkfs.xfs -f -L gentoo "$ROOT_TGT" ;;
        f2fs)  command -v mkfs.f2fs >/dev/null || die "mkfs.f2fs missing in live env"; mkfs.f2fs -l gentoo "$ROOT_TGT" ;;
    esac || die "root mkfs failed"
    ok "root fs: $FS on $ROOT_TGT"

    # ---------------------------------------------------------- unpack -----
    step "Download + unpack stage3 ($ARCH, $INIT)"
    mkdir -p "$GROOT"
    if ! mountpoint -q "$GROOT"; then mount "$ROOT_TGT" "$GROOT" || die "mount failed"; fi
    [ -n "${SWAP_PART:-}" ] && swapon "$SWAP_PART" && ok "swap on"
    [ -n "${ESP_PART:-}" ] && mkdir -p "$GROOT/boot" && mount "$ESP_PART" "$GROOT/boot" && ok "ESP on /boot"

    BASE="$MIRROR/releases/$ARCH/autobuilds/"
    say "reading $BASE ..."
    STAGE_DIRS=$(wget -qO- --timeout=20 "$BASE" | grep -oE "current-stage3-${ARCH}[A-Za-z0-9-]*/" | sort -u)
    [ -n "$STAGE_DIRS" ] || die "no current-stage3-* dirs found at $BASE"
    DIR=$(pick "stage3 build ($(printf '%s\n' "$STAGE_DIRS" | wc -l) found on mirror):" $STAGE_DIRS)
    case "$DIR" in *systemd*) DIR_INIT=systemd ;; *) DIR_INIT=openrc ;; esac
    [ "$DIR_INIT" = "$INIT" ] || warn "stage3 init ($DIR_INIT) != profile init ($INIT) - eselect will fix it, but matching is cleaner"
    DIRPAGE=$(wget -qO- --timeout=20 "$BASE$DIR" | grep -oE "stage3-${ARCH}[A-Za-z0-9._/-]*\.tar\.xz" | sort -u | tail -1)
    DIRPAGE="${DIRPAGE##*/}"   # some listings nest paths; keep just the filename
    [ -n "$DIRPAGE" ] || die "could not find a stage3 tarball under $BASE$DIR"
    say "stage3: ${Y}$DIRPAGE${X}"
    cd /var/tmp || die "cannot cd /var/tmp"
    SHA_OK=0
    wget -q -O /var/tmp/stage3.sha "$BASE$DIR$DIRPAGE.sha512" 2>/dev/null && grep -qE '[0-9a-fA-F]{128}' /var/tmp/stage3.sha && SHA_OK=1
    [ $SHA_OK = 0 ] && wget -q -O /var/tmp/stage3.sha "$BASE$DIR$DIRPAGE.DIGESTS" 2>/dev/null && grep -qE '[0-9a-fA-F]{128}' /var/tmp/stage3.sha && SHA_OK=1
    [ $SHA_OK = 0 ] && warn "no usable checksum sidecar on mirror; will unpack UNVERIFIED (last resort)"
    ATTEMPT=0; VERIFIED=0
    while [ $ATTEMPT -lt 3 ] && [ $VERIFIED = 0 ]; do
        ATTEMPT=$((ATTEMPT+1))
        [ $ATTEMPT -gt 1 ] && { rm -f "$DIRPAGE"; say "re-downloading (attempt $ATTEMPT/3) ..."; }
        wget -q --show-progress -O "$DIRPAGE" "$BASE$DIR$DIRPAGE" || { warn "wget failed; retrying"; continue; }
        MAGIC=$(head -c 6 "$DIRPAGE" | od -An -tx1 | tr -d ' \n')
        [ "$MAGIC" = "fd377a585a00" ] || { warn "download is not xz (starts $MAGIC) - mirror served junk; retrying"; continue; }
        if [ $SHA_OK = 1 ]; then
            ACTUAL=$(sha512sum "$DIRPAGE" | awk '{print $1}')
            if grep -qiF "$ACTUAL" /var/tmp/stage3.sha; then
                VERIFIED=1; ok "SHA512 verified (attempt $ATTEMPT): ${ACTUAL:0:16}..."
            else
                warn "hash mismatch (attempt $ATTEMPT): computed sha512 ${ACTUAL:0:16}... not in sidecar"
            fi
        else
            VERIFIED=1
        fi
    done
    if [ $VERIFIED = 0 ]; then
        say "${R}expected hashes on mirror:${X}"; grep -Eio '[0-9a-f]{128}' /var/tmp/stage3.sha | cut -c1-24
        die "SHA512 mismatch after 3 attempts - pick a different mirror and re-run"
    fi
    say "unpacking (grab a snack) ..."
    tar -xpv --xattrs -f "$DIRPAGE" -C "$GROOT" || die "unpack failed"
    ok "stage3 unpacked"

    # ---------------------------------------------------- make.conf etc. ---
    step "Writing /etc/portage/make.conf"
    USE_STR=""; for u in $USE_LIST; do USE_STR="$USE_STR $u"; done
    [ $LTO = 1 ] && LTO_FLAGS=" -flto=auto -fno-fat-lto-objects" && LTO_USE="lto"
    mkdir -p "$GROOT/etc/portage"
    cat > "$GROOT/etc/portage/make.conf" <<EOF
# Generated by gentoo-install.sh $(date -Is)
CHOST="$([ $ARCH = amd64 ] && echo x86_64-pc-linux-gnu || echo aarch64-unknown-linux-gnu)"
COMMON_FLAGS="$MARCH $OPT -pipe${LTO_FLAGS:-}"
CFLAGS="\${COMMON_FLAGS}"
CXXFLAGS="\${COMMON_FLAGS}"
FCFLAGS="\${COMMON_FLAGS}"
FFLAGS="\${COMMON_FLAGS}"
MAKEOPTS="-j$MAKE_JOBS"
VIDEO_CARDS="$VIDEO"
INPUT_DEVICES="libinput"
USE="$USE_STR ${LTO_USE:-}"
GENTOO_MIRRORS="$MIRROR"
$([ -n "$SYNC_URL" ] && echo "SYNC=\"$SYNC_URL\"")
ACCEPT_LICENSE="-* @FREE @BINARY-REDISTRIBUTABLE"
$([ $CCACHE = 1 ] && echo 'FEATURES="ccache"' && echo 'CCACHE_SIZE="4G"')
$([ $LTO = 1 ] && echo 'FEATURES="${FEATURES} lto"')
EOF
    [ $EFI = 1 ] && echo 'GRUB_PLATFORMS="efi-64"' >> "$GROOT/etc/portage/make.conf"
    cat "$GROOT/etc/portage/make.conf"

    step "fstab"
    (
        echo "# /etc/fstab: generated by gentoo-install.sh"
        printf 'UUID=%s  /  %s  defaults,noatime  0 1\n' "$(blkid -s UUID -o value "$ROOT_TGT")" "$FS"
        [ -n "${SWAP_PART:-}" ] && printf 'UUID=%s  none  swap  sw  0 0\n' "$(blkid -s UUID -o value "$SWAP_PART")"
        [ -n "${ESP_PART:-}" ] && printf 'UUID=%s  /boot  vfat  defaults  0 2\n' "$(blkid -s UUID -o value "$ESP_PART")"
    ) > "$GROOT/etc/fstab"
    cat "$GROOT/etc/fstab"

    # ------------------------------------------------- chroot handoff ------
    step "Preparing chroot"
    mount --rbind /dev  "$GROOT/dev"  2>/dev/null || true
    mount --make-rslave "$GROOT/dev"  2>/dev/null || true
    mount -t proc proc  "$GROOT/proc" 2>/dev/null || true
    mount --rbind /sys  "$GROOT/sys"  2>/dev/null || true
    mount --make-rslave "$GROOT/sys"  2>/dev/null || true
    cp -fL /etc/resolv.conf "$GROOT/etc/resolv.conf" && ok "DNS copied into chroot"

    chroot "$GROOT" eselect profile list 2>/dev/null | grep -qF "$PROFILE" || warn "profile '$PROFILE' not in list; stage 2 will retry via eselect"
    chroot "$GROOT" eselect profile set-name "$PROFILE" >/dev/null 2>&1 && ok "profile set: $PROFILE"

    cp -f "$SELF" "$GROOT/root/gentoo-install.sh"
    # persist choices for stage 2
    cat > "$STATEFILE" <<EOF
# gentoo-install stage1 state $(date -Is)
ARCH=$ARCH; DISK=$DISK; EFI=$EFI; INIT=$INIT; PROFILE=\"$PROFILE\"; FS=$FS
ROOT_PART=$ROOT_PART; ROOT_TGT=$ROOT_TGT; ENCRYPT=$ENCRYPT
ESP_PART=${ESP_PART:-}; SWAP_PART=${SWAP_PART:-}
MIRROR=\"$MIRROR\"; SYNC_URL=\"$SYNC_URL\"; HAS_WIFI=$HAS_WIFI
HOSTNAME=$HOSTNAME; MARCH=\"$MARCH\"; OPT=$OPT; LTO=$LTO; CCACHE=$CCACHE
USE_LIST=\"$USE_LIST\"; VIDEO=\"$VIDEO\"
EOF
    ok "state saved: $STATEFILE (script copied to /root/gentoo-install.sh)"

    hr
    say "${G}Stage 1 complete. ~30-90 min of compiling ahead depending on choices.${X}"
    if yesno "enter chroot and start stage 2 now?" y; then
        say "${C}spawning stage 2 inside the chroot...${X}"
        chroot "$GROOT" /bin/bash /root/gentoo-install.sh stage2
    else
        say "resume anytime with:  ${Y}chroot $GROOT /bin/bash /root/gentoo-install.sh stage2${X}"
    fi
}

# ===========================================================================
#                              STAGE 2
# ===========================================================================
stage2() {
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    say "${B}"
    say "============================================================"
    say "  Gentoo installer - STAGE 2 (inside the chroot)  v$VERSION"
    say "  system config / kernel / bootloader / packages / users"
    say "============================================================${X}"
    [ -f "$STATEFILE" ] || die "stage-1 state not found at $STATEFILE - run stage 1 first (state lives in /mnt/gentoo/root/)"
    # shellcheck disable=SC1090
    . "$STATEFILE"
    ok "stage-1 state loaded (disk=$DISK init=$INIT fs=$FS)"

    step "Portage sync"
    if [ -z "$SYNC_URL" ]; then
        yesno "run 'emerge --webrsync' now?" y && emerge --webrsync || warn "skipped sync - packages may be stale"
    else
        yesno "sync portage tree now (~2-5 min)?" y && emerge --sync --quiet || warn "sync skipped"
    fi

    step "Timezone"
    TZ=$(ask "IANA timezone" "America/New_York")
    [ -f "/usr/share/zoneinfo/$TZ" ] || warn "zoneinfo for '$TZ' missing in stage3; installing sys-libs/timezone-data shortly"
    if [ $INIT = systemd ]; then
        systemd-hwclock 2>/dev/null; ln -sf "/usr/share/zoneinfo/$TZ" /etc/localtime; echo "$TZ" > /etc/timezone
    else
        ln -sf "/usr/share/zoneinfo/$TZ" /etc/localtime; echo "$TZ" > /etc/timezone
        sed -i 's/^clock=.*/clock=UTC/' /etc/conf.d/hwclock.sh 2>/dev/null || true
    fi
    ok "timezone: $TZ"

    step "Locale + keymap"
    LOCALE=$(ask "locale" "en_US.UTF-8")
    echo "$LOCALE UTF-8" >> /etc/locale.gen
    sed -i "s|^#\( $LOCALE\)|\1|" /etc/locale.gen 2>/dev/null || true
    command -v locale-gen >/dev/null && locale-gen || warn "locale-gen unavailable until world updates; re-run after"
    if [ $INIT = openrc ]; then
        KEYMAP=$(ask "keymap (loadkeys name)" "us")
        sed -i "s/^KEYMAP=.*/KEYMAP=\"$KEYMAP\"/" /etc/conf.d/keymaps 2>/dev/null || true
    fi

    step "Hostname"
    echo "$HOSTNAME" > /etc/hostname
    sed -i "s/^hostname=.*/hostname=$HOSTNAME/" /etc/conf.d/hostname 2>/dev/null || true
    ok "hostname: $HOSTNAME"

    step "Root password"
    say "${D}You type it at the prompt - this script never sees or stores it.${X}"
    passwd || warn "passwd failed; set one later with 'passwd root'"

    step "Kernel"
    KERNEL=$(pick "Kernel:" \
        "distribution kernel, binary (gentoo-kernel-bin - fast)" \
        "distribution kernel, built (gentoo-kernel)" \
        "genkernel (gentoo-sources, automated config)" \
        "manual - I'll do make menuconfig myself later")
    [ $ENCRYPT = 1 ] && [ "$KERNEL" != "genkernel (gentoo-sources, automated config)" ] && \
        { warn "LUKS root needs an initramfs - forcing genkernel"; KERNEL="genkernel (gentoo-sources, automated config)"; }
    MICROCODE=$(multiselect "CPU microcode packages:" "intel-microcode" "amd-ucode")
    emerge --oneshot --noreplace sys-kernel/linux-firmware $MICROCODE

    step "Bootloader"
    if [ $EFI = 1 ]; then
        BOOTLOADER=$(pick "Bootloader:" \
            "GRUB (UEFI - works everywhere)" \
            "systemd-boot (fast; systemd only)" \
            "none - I'll sort it myself")
    else
        BOOTLOADER=$(pick "Bootloader:" "GRUB (BIOS)" "none - I'll sort it myself")
    fi
    [ $INIT = systemd ] && [ "$BOOTLOADER" = "systemd-boot (fast; systemd only)" ] || true

    step "Network stack"
    NET=$(pick "Networking:" "NetworkManager (DHCP + wifi GUI)" "dhcpcd (lightweight DHCP)" "netifrc manual config (OpenRC classic)")
    NETPKGS=""
    case "$NET" in
        NetworkManager*) NETPKGS="net-misc/networkmanager" ;;
        dhcpcd*)         NETPKGS="net-misc/dhcpcd" ;;
        *)               NETPKGS="net-misc/netifrc" ;;
    esac
    [ $HAS_WIFI = 1 ] && NETPKGS="$NETPKGS net-wireless/wpa_supplicant"

    # ---------------------------------------------------- big installs -----
    step "Base system update (@world)"
    UPD=$(pick "How to run 'emerge -DN @world':" \
        "interactive, ask me first (-a)" \
        "unattended (-g, background-friendly)" \
        "pretend only (-p)")
    case "$UPD" in
        interactive*) emerge -avDN @world ;;
        unattended*)  emerge -gqDN @world || warn "world update failed; check the log and re-run emerge -avDN @world" ;;
        *)            emerge -pvDN @world; warn "update skipped; re-run emerge -avDN @world after reviewing" ;;
    esac
    command -v locale-gen >/dev/null && locale-gen || true

    step "Kernel install"
    case "$KERNEL" in
        *gentoo-kernel-bin*) emerge -avn --noreplace sys-kernel/gentoo-kernel-bin ;;
        "distribution kernel, built (gentoo-kernel)") emerge -avn --noreplace sys-kernel/gentoo-kernel ;;
        genkernel*)
            emerge -avn --noreplace sys-kernel/gentoo-sources sys-kernel/genkernel
            GK_FLAGS=""
            [ $ENCRYPT = 1 ] && GK_FLAGS="--luks"
            say "genkernel will auto-configure the kernel (takes a while) ..."
            genkernel $GK_FLAGS --install all || die "genkernel failed"
            ;;
        manual*) warn "skipping kernel build - later: emerge gentoo-sources, cd /usr/src/linux && make menuconfig..." ;;
    esac

    step "Bootloader install"
    if [ $ENCRYPT = 1 ]; then
        ROOT_PART_UUID=$(blkid -s UUID -o value "$ROOT_PART")
        # crypttab for systemd-cryptsetup / init scripts
        echo "groot UUID=$ROOT_PART_UUID none" >> /etc/crypttab
        # kernel cmdline so the initramfs unlocks before mounting real root
        if [ -f /etc/default/grub ]; then
            sed -i "s|^GRUB_CMDLINE_LINUX=.*|GRUB_CMDLINE_LINUX=\"crypt_root=UUID=$ROOT_PART_UUID real_root=/dev/mapper/groot\"" /etc/default/grub
        fi
        ok "crypttab + crypt_root cmdline wired for UUID=$ROOT_PART_UUID"
    fi
    case "$BOOTLOADER" in
        GRUB*)
            emerge -avn --noreplace sys-boot/grub
            if [ $EFI = 1 ]; then
                grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=Gentoo --removable
            else
                grub-install --target=i386-pc "$DISK"
            fi
            [ -d /boot/grub ] || mkdir -p /boot/grub
            grub-mkconfig -o /boot/grub/grub.cfg
            ;;
        systemd-boot*)
            bootctl install || warn "bootctl install failed"
            ;;
        none*) warn "no bootloader installed - you'll need one before reboot!" ;;
    esac

    step "Networking install"
    emerge -avn --noreplace $NETPKGS
    if [ $HAS_WIFI = 1 ] && [ "$NET" = "NetworkManager (DHCP + wifi GUI)" ]; then
        SSID=$(ask_required "wifi network name (SSID)")
        printf '%b' "${C}wifi password (typed here stays on disk in NM config, mode 0600): ${X}"; read -rs WIFIKP; echo
        mkdir -p /etc/NetworkManager/system-connections
        cat > "/etc/NetworkManager/system-connections/$SSID.nmconnection" <<NMEOF
[connection]
id=$SSID
type=wifi
autoconnect=true

[wifi]
mode=infrastructure
ssid=$SSID

[wifi-security]
key-mgmt=wpa-psk
psk=$WIFIKP
NMEOF
        chmod 600 "/etc/NetworkManager/system-connections/$SSID.nmconnection"
        ok "wifi connection written: $SSID"
    fi
    if [ $INIT = openrc ]; then
        case "$NET" in
            NetworkManager*) rc-update add NetworkManager default ;;
            dhcpcd*)         rc-update add dhcpcd default ;;
            *) warn "netifrc: configure /etc/conf.d/net then 'rc-update add net.eth0 default'" ;;
        esac
    else
        case "$NET" in
            NetworkManager*) systemctl enable NetworkManager 2>/dev/null || true ;;
            dhcpcd*)         systemctl enable dhcpcd 2>/dev/null || true ;;
            *) warn "systemd-networkd is enabled by default with the systemd profile" ;;
        esac
    fi

    step "Desktop / extras"
    DESKTOP=$(pick "Desktop / login:" \
        "Plasma (plasma-meta)" "GNOME (gnome)" "Xfce (xfce4-meta)" "Cinnamon (cinnamon-meta)" \
        "MATE" "no desktop (just a terminal)")
    case "$DESKTOP" in
        Plasma*) DESKTOP_PKG="kde-plasma/plasma-meta" ;;
        GNOME*)  DESKTOP_PKG="gnome-base/gnome" ;;
        Xfce*)   DESKTOP_PKG="xfce-base/xfce4-meta" ;;
        Cinnamon*) DESKTOP_PKG="gnome-extra/cinnamon-meta" ;;
        MATE)    DESKTOP_PKG="mate-base/mate" ;;
        *)       DESKTOP_PKG="" ;;
    esac
    [ -n "$DESKTOP_PKG" ] && emerge -avn --noreplace "$DESKTOP_PKG"

    BROWSER=$(pick "Browser (warning: Firefox/Chromium from source = LONG build):" \
        "firefox" "firefox-bin (binary, fast install)" "chromium" "none")
    case "$BROWSER" in
        firefox)      emerge -avn --noreplace www-client/firefox ;;
        "firefox-bin (binary, fast install)") emerge -avn --noreplace www-client/firefox-bin ;;
        chromium)     emerge -avn --noreplace www-client/chromium ;;
    esac

    EXTRAS=$(multiselect "Extra packages:" \
        "sys-process/cronie" "net-misc/openssh" "app-editors/neovim" "dev-vcs/git" \
        "app-admin/htop" "app-misc/fzf" "media-sound/wireplumber" "app-crypt/gnupg" \
        "net-analyzer/nmap" "app-arch/p7zip")
    [ -n "$EXTRAS" ] && emerge -avn --noreplace $EXTRAS

    step "User accounts"
    USERS=""
    say "Enter usernames to create (empty line when done):"
    while :; do
        u=$(ask "username")
        [ -z "$u" ] && break
        [ "$u" = root ] && { warn "that's root, silly"; continue; }
        useradd -m -G wheel,audio,video,plugdev,users,lpadmin "$u" && ok "created: $u" && USERS="$USERS $u"
    done
    for u in $USERS; do
        say "Setting password for $u (type at prompt):"
        passwd "$u" || warn "passwd $u failed"
    done
    yesno "install sudo for the wheel group?" y && emerge -avn --noreplace app-admin/sudo

    step "Services"
    if [ $INIT = openrc ]; then
        yesno "enable sshd at boot?" n && rc-update add sshd default
        case "$EXTRAS" in *cronie*) rc-update add cronie default ;; esac
        [ "$DESKTOP_PKG" ] && yesno "enable the login/display manager at boot?" y && rc-update add display-manager default
    else
        yesno "enable sshd at boot?" n && systemctl enable sshd 2>/dev/null || true
        systemctl enable cronie 2>/dev/null || true
    fi

    step "Finish"
    env-update && source /etc/profile 2>/dev/null
    eselect news read 2>/dev/null | head -5 || true
    hr
    say "${G}Stage 2 done. Final touches if you skipped anything:${X}"
    say "  - review config: etc-update"
    say "  - kernel was skipped? emerge gentoo-sources + genkernel --install all"
    say "  - no bootloader? fix it BEFORE rebooting"
    hr
    say "exit the chroot, then as root on the live USB:"
    say "  ${Y}umount -l $GROOT && cd / && reboot${X}"
    say "Good luck with your new Gentoo \o/"
}

# ============================== entry point =================================
usage() {
    cat <<U
gentoo-install.sh v$VERSION <stage1|stage2>
  stage1 - run from the live USB as root: disk/stage3/make.conf/chroot handoff
  stage2 - run inside the chroot (stage1 can chain into it automatically)
U
}
case "${1:-}" in
    stage1) stage1 ;;
    stage2) stage2 ;;
    *) usage; exit 1 ;;
esac
