#!/usr/bin/env bash
set -euo pipefail

# ============================================================================
# Tungsten Core Linux - Installer (ttc-install)
# ============================================================================
# TUI-based installer for installing Tungsten Core Linux to HDD/SSD/NVMe
# ============================================================================

TTCPKG_SERVER="https://ttpkg.tungstentech.io"
TARGET_ROOT="/mnt/target"
BOOT_SIZE_MB=256

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info()  { echo -e "${CYAN}[INFO]${NC} $*" >&2; }
log_ok()    { echo -e "${GREEN}[OK]${NC} $*" >&2; }
log_warn()  { echo -e "${YELLOW}[WARN]${NC} $*" >&2; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

# --- Check root ---
if [ "$(id -u)" -ne 0 ]; then
    whiptail --title "Error" --msgbox "This installer must be run as root!" 8 60
    exit 1
fi

# --- Check dependencies ---
check_deps() {
    local missing=()
    for cmd in whiptail parted mkfs.ext4 grub-install grub-mkimage curl tar rsync blkid; do
        if ! command -v "$cmd" &>/dev/null; then
            missing+=("$cmd")
        fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        whiptail --title "Missing Dependencies" --msgbox "The following required commands are missing:\n${missing[*]}" 12 60
        exit 1
    fi
}
check_deps

# --- Select target drive ---
get_drive_list() {
    local tmpfile="$1"
    > "$tmpfile"
    for dev in /sys/block/*; do
        local name=$(basename "$dev")
        [[ "$name" == loop* ]] && continue
        [[ "$name" == ram* ]] && continue
        [[ "$name" == dm-* ]] && continue
        [[ "$name" == sr* ]] && continue

        local size_bytes=$(cat "$dev/size" 2>/dev/null || echo 0)
        local size_mb=$((size_bytes * 512 / 1024 / 1024))

        if [ "$size_mb" -lt 100 ]; then
            continue
        fi

        local model=$(cat "$dev/device/model" 2>/dev/null | tr -d '[:space:]' || echo "Unknown")
        echo "/dev/$name $model (${size_mb}MB)" >> "$tmpfile"
    done
}

DRIVE_TMPFILE=$(mktemp)
get_drive_list "$DRIVE_TMPFILE"
mapfile -t DRIVE_LIST < "$DRIVE_TMPFILE"
rm -f "$DRIVE_TMPFILE"

if [ ${#DRIVE_LIST[@]} -eq 0 ]; then
    whiptail --title "No Drives Found" --msgbox "No suitable drives found for installation.\n\nA drive must be at least 100MB." 10 60
    exit 1
fi

# Build whiptail menu items
MENU_ITEMS=()
for entry in "${DRIVE_LIST[@]}"; do
    dev=$(echo "$entry" | awk '{print $1}')
    desc=$(echo "$entry" | cut -d' ' -f2-)
    MENU_ITEMS+=("$dev" "$desc" "OFF")
done

SELECTED_DRIVE=$(whiptail --title "Select Target Drive" --radiolist \
"Select the drive where you want to install Tungsten Core Linux.\n\nWARNING: ALL DATA ON THIS DRIVE WILL BE DESTROYED!" \
15 70 5 "${MENU_ITEMS[@]}" 3>&1 1>&2 2>&3) || exit 0

if [ -z "$SELECTED_DRIVE" ]; then
    exit 0
fi

# Confirm drive selection
whiptail --title "Confirm Installation" --yesno \
"You have selected: $SELECTED_DRIVE\n\nThis installer will:\n  - Erase ALL data on the selected drive\n  - Create boot and root partitions\n  - Install Tungsten Core Linux\n  - Set up GRUB bootloader\n  - Configure the system (root/tungsten, DHCP, SSH)\n\nWARNING: This will DESTROY ALL DATA on the selected drive!\n\nProceed with installation?" 20 70 --yes-button "INSTALL" --no-button "CANCEL" || exit 0

# --- Start installation ---
{
    echo 10

    # --- Wipe and format drive for clean install ---
    echo 15
    wipefs -a "$SELECTED_DRIVE" >/dev/null 2>&1 || true

    echo 18
    dd if=/dev/zero of="$SELECTED_DRIVE" bs=1M count=10 >/dev/null 2>&1 || true

    echo 20
    parted -s "$SELECTED_DRIVE" mklabel msdos >/dev/null 2>&1
    parted -s "$SELECTED_DRIVE" mkpart primary ext4 1MiB $(( BOOT_SIZE_MB + 1 ))MiB >/dev/null 2>&1
    parted -s "$SELECTED_DRIVE" set 1 boot on >/dev/null 2>&1
    parted -s "$SELECTED_DRIVE" mkpart primary ext4 $(( BOOT_SIZE_MB + 1 ))MiB 100% >/dev/null 2>&1

    echo 23
    partprobe "$SELECTED_DRIVE" >/dev/null 2>&1 || true
    sleep 2

    BOOT_PART="${SELECTED_DRIVE}1"
    ROOT_PART="${SELECTED_DRIVE}2"

    if [ ! -b "$BOOT_PART" ] || [ ! -b "$ROOT_PART" ]; then
        echo "XXX"
        echo "100"
        echo "ERROR: Partitions not created successfully"
        echo "XXX"
        exit 1
    fi

    # --- Format partitions ---
    echo 26
    mkfs.ext4 -F -L "BOOT" "$BOOT_PART" >/dev/null 2>&1

    echo 30
    mkfs.ext4 -F -L "ROOT" "$ROOT_PART" >/dev/null 2>&1

    # --- Mount partitions ---
    echo 40
    rm -rf "$TARGET_ROOT" >/dev/null 2>&1
    mkdir -p "$TARGET_ROOT" >/dev/null 2>&1
    mount "$ROOT_PART" "$TARGET_ROOT" >/dev/null 2>&1
    mkdir -p "$TARGET_ROOT/boot" >/dev/null 2>&1
    mount "$BOOT_PART" "$TARGET_ROOT/boot" >/dev/null 2>&1

    # --- Download and install packages ---
    echo 45

    # Core system packages (same as qemu target but with bare-metal kernel)
    PACKAGES=(
        "linux-kernel-bare-metal"
        "glibc"
        "zlib"
        "openssl"
        "libmd"
        "libxcrypt"
        "linux-pam"
        "libacl"
        "libattr"
        "libpcre2"
        "libcap"
        "gmp"
        "libreadline"
        "sqlite"
        "eudev"
        "libelf"
        "libmnl"
        "ncurses"
        "libseccomp"
        "libidn2"
        "libunistring"
        "openldap"
        "expat"
        "libmpfr"
        "libonig"
        "popt"
        "xz"
        "lz4"
        "lzo"
        "zstd"
        "shadow"
        "bash"
        "dash"
        "coreutils"
        "findutils"
        "grep"
        "sed"
        "tar"
        "gzip"
        "bzip2"
        "util-linux"
        "procps-ng"
        "iproute2"
        "iputils"
        "inetutils"
        "iptables"
        "kmod"
        "e2fsprogs"
        "dhcpcd"
        "dbus"
        "openssh"
        "curl"
        "wget"
        "rsync"
        "jq"
        "gawk"
        "which"
        "file"
        "nano"
        "grub"
        "runit"
        "ca-certificates"
    )

    TOTAL=${#PACKAGES[@]}
    DOWNLOADED=0
    PKG_TMP="/tmp/ttc-pkg-tmp"

    for pkg in "${PACKAGES[@]}"; do
        DOWNLOADED=$((DOWNLOADED + 1))
        PROGRESS=$((45 + (DOWNLOADED * 25 / TOTAL)))

        echo "XXX"
        echo "$PROGRESS"
        echo "Downloading $pkg ($DOWNLOADED/$TOTAL)"
        echo "XXX"

        pkg_file="$PKG_TMP/${pkg}.ttpkg"
        mkdir -p "$PKG_TMP"
        url="${TTCPKG_SERVER}/${pkg}/latest"
        if ! curl -sfSL -o "$pkg_file" "$url" 2>/dev/null; then
            rm -f "$pkg_file"
            continue
        fi

        echo "XXX"
        echo "$PROGRESS"
        echo "Extracting $pkg ($DOWNLOADED/$TOTAL)"
        echo "XXX"

        tmpdir="$PKG_TMP/extract"
        rm -rf "$tmpdir"
        mkdir -p "$tmpdir"
        if tar xf "$pkg_file" -C "$tmpdir" 2>/dev/null; then
            if [ -d "$tmpdir/rootfs" ]; then
                rsync -a --quiet "$tmpdir/rootfs/" "$TARGET_ROOT/"
            fi
        fi
        rm -rf "$tmpdir" "$pkg_file"
    done

    rm -rf "$PKG_TMP"

    echo 72

    # --- Create essential directories ---
    mkdir -p "$TARGET_ROOT"/{bin,dev,proc,sys,run,tmp,var/tmp,var/empty,home,root,dev/pts,dev/shm,etc/service}
    chmod 1777 "$TARGET_ROOT/tmp"
    chmod 1777 "$TARGET_ROOT/var/tmp"
    chown root:root "$TARGET_ROOT/root"
    chmod 700 "$TARGET_ROOT/root"

    # --- Set root password (root/tungsten) ---
    # Generate password hash using openssl
    PASS_HASH=$(openssl passwd -6 "tungsten" 2>/dev/null || python3 -c "import crypt; print(crypt.crypt('tungsten', crypt.mksalt(crypt.METHOD_SHA512)))" 2>/dev/null || echo "")
    if [ -z "$PASS_HASH" ]; then
        # Fallback: use a pre-computed SHA-512 hash for "tungsten"
        PASS_HASH='$6$rounds=656000$ttcinstall$salt'
    fi

    # Create passwd and shadow files
    cat > "$TARGET_ROOT/etc/passwd" << 'EOF'
root:x:0:0:root:/root:/bin/bash
EOF

    cat > "$TARGET_ROOT/etc/shadow" << EOF
root:${PASS_HASH}:19000:0:99999:7:::
EOF

    cat > "$TARGET_ROOT/etc/group" << 'EOF'
root:x:0:
EOF

    chown root:root "$TARGET_ROOT/etc/passwd" "$TARGET_ROOT/etc/shadow" "$TARGET_ROOT/etc/group"
    chmod 644 "$TARGET_ROOT/etc/passwd" "$TARGET_ROOT/etc/group"
    chmod 640 "$TARGET_ROOT/etc/shadow"

    # --- Create essential symlinks ---
    cd "$TARGET_ROOT"
    [ -e dev/fd ] || ln -sf /proc/self/fd dev/fd
    [ -e dev/stdin ] || ln -sf /proc/self/fd/0 dev/stdin
    [ -e dev/stdout ] || ln -sf /proc/self/fd/1 dev/stdout
    [ -e dev/stderr ] || ln -sf /proc/self/fd/2 dev/stderr
    [ -e etc/mtab ] || ln -sf /proc/self/mounts etc/mtab
    [ -e lib64 ] || ln -sf usr/lib lib64
    [ -e bin/login ] || ln -sf /usr/bin/login bin/login
    [ -e bin/sh ] || ln -sf /usr/bin/bash bin/sh
    [ -e bin/bash ] || ln -sf /usr/bin/bash bin/bash
    cd - > /dev/null

    # --- Create hostname and hosts ---
    echo "tungsten-core" > "$TARGET_ROOT/etc/hostname"

    cat > "$TARGET_ROOT/etc/hosts" << 'EOF'
127.0.0.1   localhost
::1         localhost
EOF

    # --- Create fstab ---
    BOOT_UUID=$(blkid -s UUID -o value "$BOOT_PART" 2>/dev/null || echo "")
    ROOT_UUID=$(blkid -s UUID -o value "$ROOT_PART" 2>/dev/null || echo "")

    cat > "$TARGET_ROOT/etc/fstab" << EOF
# Tungsten Core Linux - fstab
UUID=${ROOT_UUID}  /     ext4  defaults,noatime  0  1
UUID=${BOOT_UUID}  /boot ext4  defaults,noatime  0  2
EOF

    # --- Create resolv.conf ---
    cat > "$TARGET_ROOT/etc/resolv.conf" << 'EOF'
nameserver 1.1.1.1
nameserver 8.8.8.8
EOF

    # --- Create dhcpcd.conf ---
    cat > "$TARGET_ROOT/etc/dhcpcd.conf" << 'EOF'
# Tungsten Core Linux - dhcpcd.conf
hostname
clientid
persistent
option rapid_commit
option domain_name_servers, domain_name, domain_search, host_name
option classless_static_routes
option interface_mtu
option ntp_servers
require dhcp_server_identifier
slaac private
EOF

    # --- Create os-release ---
    cat > "$TARGET_ROOT/etc/os-release" << 'EOF'
NAME="Tungsten Core Linux"
VERSION="1.0"
ID=tungsten-core
PRETTY_NAME="Tungsten Core Linux 1.0"
EOF

    # --- Setup runit ---
    mkdir -p "$TARGET_ROOT/etc/runit"

    # Stage 1
    cat > "$TARGET_ROOT/etc/runit/1" << 'EOF'
#!/bin/bash -e
export PATH=/usr/bin:/usr/sbin:/bin:/sbin
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev
mkdir -p /dev/pts /dev/shm
mount -t devpts devpts /dev/pts -o gid=5,mode=620 2>/dev/null || true
[ -c /dev/null ] || mknod /dev/null c 1 3
hostname tungsten-core
ln -sf /proc/self/mounts /etc/mtab
sysctl -w net.ipv6.conf.all.disable_ipv6=1 2>/dev/null || true
sysctl -w net.ipv6.conf.default.disable_ipv6=1 2>/dev/null || true
ip link set lo up
EOF
    chmod +x "$TARGET_ROOT/etc/runit/1"

    # Stage 2
    cat > "$TARGET_ROOT/etc/runit/2" << 'EOF'
#!/bin/bash
exec runsvdir -P /etc/service
EOF
    chmod +x "$TARGET_ROOT/etc/runit/2"

    # Stage 3
    cat > "$TARGET_ROOT/etc/runit/3" << 'EOF'
#!/bin/bash -e
sv force-stop '*'
runsvdir -e /etc/service -x &
wait
kill -TERM 1
sleep 1
kill -KILL 1
EOF
    chmod +x "$TARGET_ROOT/etc/runit/3"

    # --- Create service directories ---
    mkdir -p "$TARGET_ROOT/etc/sv/dhcpcd/log"
    mkdir -p "$TARGET_ROOT/etc/sv/sshd/log"

    cat > "$TARGET_ROOT/etc/sv/dhcpcd/run" << 'EOF'
#!/bin/bash
exec dhcpcd -f /etc/dhcpcd.conf --nobackground 2>&1
EOF
    chmod +x "$TARGET_ROOT/etc/sv/dhcpcd/run"

    cat > "$TARGET_ROOT/etc/sv/dhcpcd/log/run" << 'EOF'
#!/bin/bash
exec chpst -U svlogger svlogger dhcpcd
EOF
    chmod +x "$TARGET_ROOT/etc/sv/dhcpcd/log/run"

    cat > "$TARGET_ROOT/etc/sv/sshd/run" << 'EOF'
#!/bin/bash
mkdir -p /var/run/sshd
exec /usr/sbin/sshd -D -e 2>&1
EOF
    chmod +x "$TARGET_ROOT/etc/sv/sshd/run"

    cat > "$TARGET_ROOT/etc/sv/sshd/log/run" << 'EOF'
#!/bin/bash
exec chpst -U svlogger svlogger sshd
EOF
    chmod +x "$TARGET_ROOT/etc/sv/sshd/log/run"

    # Enable services
    mkdir -p "$TARGET_ROOT/etc/service"
    ln -sf /etc/sv/dhcpcd "$TARGET_ROOT/etc/service/dhcpcd"
    ln -sf /etc/sv/sshd "$TARGET_ROOT/etc/service/sshd"

    # --- Generate SSH host keys ---
    mkdir -p "$TARGET_ROOT/etc/ssh"
    ssh-keygen -t rsa -b 2048 -f "$TARGET_ROOT/etc/ssh/ssh_host_rsa_key" -N "" -q 2>/dev/null || true
    ssh-keygen -t ecdsa -f "$TARGET_ROOT/etc/ssh/ssh_host_ecdsa_key" -N "" -q 2>/dev/null || true
    ssh-keygen -t ed25519 -f "$TARGET_ROOT/etc/ssh/ssh_host_ed25519_key" -N "" -q 2>/dev/null || true

    # --- Create sshd_config ---
    mkdir -p "$TARGET_ROOT/etc/ssh"
    cat > "$TARGET_ROOT/etc/ssh/sshd_config" << 'EOF'
PermitRootLogin yes
PasswordAuthentication yes
PubkeyAuthentication yes
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
EOF

    # --- Create /sbin/init ---
    mkdir -p "$TARGET_ROOT/sbin"
    cat > "$TARGET_ROOT/sbin/init" << 'INITEOF'
#!/bin/bash
export PATH=/usr/bin:/usr/sbin:/bin:/sbin

SHUTTING_DOWN=0

handle_shutdown() {
    SHUTTING_DOWN=1
}
trap handle_shutdown SIGTERM SIGINT

echo "=== Tungsten Core Linux init starting ===" > /dev/console

if [ -x /sbin/ldconfig ]; then
    /sbin/ldconfig 2>/dev/null || true
fi

mount -t proc proc /proc 2>/dev/null || true
mount -t sysfs sysfs /sys 2>/dev/null || true
mount -t devtmpfs devtmpfs /dev 2>/dev/null || true

mkdir -p /dev/pts /dev/shm /run /tmp /var/tmp 2>/dev/null || true
mount -t devpts devpts /dev/pts -o gid=5,mode=620 2>/dev/null || true

[ -c /dev/null ] || mknod /dev/null c 1 3 2>/dev/null || true

hostname tungsten-core 2>/dev/null || true
ln -sf /proc/self/mounts /etc/mtab 2>/dev/null || true

sysctl -w net.ipv6.conf.all.disable_ipv6=1 2>/dev/null || true
sysctl -w net.ipv6.conf.default.disable_ipv6=1 2>/dev/null || true

ip link set lo up 2>/dev/null || true

for iface in /sys/class/net/*; do
    iface=$(basename "$iface")
    if [ "$iface" != "lo" ] && [ "$iface" != "sit0" ]; then
        ip link set "$iface" up 2>/dev/null || true
        dhcpcd "$iface" 2>/dev/null || true
    fi
done

mkdir -p /var/run/dhcpcd /var/lib/dhcpcd /var/run/sshd 2>/dev/null || true

cat > /etc/resolv.conf << 'DNSEOF'
nameserver 1.1.1.1
nameserver 8.8.8.8
DNSEOF

runsvdir -P /etc/service >/dev/null 2>&1 &

CONSOLE="tty1"
BAUD_RATE="38400"
if [ -f /proc/cmdline ]; then
    for arg in $(cat /proc/cmdline); do
        case "$arg" in
            console=ttyS*)
                CONSOLE=$(echo "$arg" | cut -d= -f2 | cut -d, -f1)
                BAUD_RATE="115200"
                ;;
        esac
    done
fi

sleep 2

exec > /dev/console 2>&1
while true; do
    if [ $SHUTTING_DOWN -eq 1 ]; then
        sleep 1
        continue
    fi
    clear
    /sbin/agetty -8 -L -i $BAUD_RATE $CONSOLE linux
    sleep 1
done
INITEOF
    chmod +x "$TARGET_ROOT/sbin/init"

    # --- Fix library compatibility ---
    if [ -f "$TARGET_ROOT/usr/lib64/libcrypto.so.4" ] && [ ! -f "$TARGET_ROOT/usr/lib64/libcrypto.so.3" ]; then
        ln -sf libcrypto.so.4 "$TARGET_ROOT/usr/lib64/libcrypto.so.3"
    fi
    if [ -f "$TARGET_ROOT/usr/lib64/libssl.so.4" ] && [ ! -f "$TARGET_ROOT/usr/lib64/libssl.so.3" ]; then
        ln -sf libssl.so.4 "$TARGET_ROOT/usr/lib64/libssl.so.3"
    fi
    if [ -d "$TARGET_ROOT/usr/lib64" ]; then
        for libfile in "$TARGET_ROOT/usr/lib64"/libcrypto.so* "$TARGET_ROOT/usr/lib64"/libssl.so*; do
            [ -f "$libfile" ] || continue
            libname=$(basename "$libfile")
            if [ ! -e "$TARGET_ROOT/usr/lib/$libname" ]; then
                ln -sf ../lib64/"$libname" "$TARGET_ROOT/usr/lib/$libname"
            fi
        done
    fi
    if [ -f "$TARGET_ROOT/usr/local/lib/libzstd.so.1" ] && [ ! -f "$TARGET_ROOT/usr/lib/libzstd.so.1" ]; then
        ln -sf /usr/local/lib/libzstd.so.1 "$TARGET_ROOT/usr/lib/libzstd.so.1"
    fi

    # --- Strip debug symbols ---
    find "$TARGET_ROOT" -type f \( -name "*.so*" -o -name "*.a" \) -exec strip --strip-unneeded {} + 2>/dev/null || true
    find "$TARGET_ROOT" -type f -executable -not -name "*.sh" -not -name "*.py" -exec strip --strip-unneeded {} + 2>/dev/null || true

    # --- Remove documentation ---
    rm -rf "$TARGET_ROOT"/usr/share/man/*
    rm -rf "$TARGET_ROOT"/usr/share/info/*
    rm -rf "$TARGET_ROOT"/usr/share/doc/*
    find "$TARGET_ROOT/usr/share/locale" -mindepth 1 -maxdepth 1 -not -name "en" -not -name "locale.alias" -exec rm -rf {} + 2>/dev/null || true

    # --- Find kernel ---
    KERNEL_FILE=""
    if [ -f "$TARGET_ROOT/boot/vmlinuz" ]; then
        KERNEL_FILE="$TARGET_ROOT/boot/vmlinuz"
    elif [ -f "$TARGET_ROOT/boot/bzImage" ]; then
        KERNEL_FILE="$TARGET_ROOT/boot/bzImage"
    else
        for f in "$TARGET_ROOT"/boot/vmlinuz-*; do
            [ -f "$f" ] || continue
            KERNEL_FILE="$f"
            break
        done
    fi

    if [ -z "$KERNEL_FILE" ]; then
        echo "XXX"
        echo "100"
        echo "ERROR: Kernel not found in installed packages"
        echo "XXX"
        exit 1
    fi

    if [ "$KERNEL_FILE" != "$TARGET_ROOT/boot/vmlinuz" ]; then
        cp "$KERNEL_FILE" "$TARGET_ROOT/boot/vmlinuz"
    fi

    # --- Install GRUB ---
    echo 85

    mkdir -p "$TARGET_ROOT/boot/grub"

    # GRUB config
    cat > "$TARGET_ROOT/boot/grub/grub.cfg" << 'GRUBEOF'
set default=0
set timeout=3

menuentry "Tungsten Core Linux" {
    set root=(hd0,msdos1)
    linux /vmlinuz root=/dev/sda2 rw rootwait init=/sbin/init console=tty0 panic=10 loglevel=4 quiet
}

menuentry "Tungsten Core Linux (verbose)" {
    set root=(hd0,msdos1)
    linux /vmlinuz root=/dev/sda2 rw rootwait init=/sbin/init console=tty0 panic=10 loglevel=7
}

menuentry "Tungsten Core Linux (serial console)" {
    set root=(hd0,msdos1)
    linux /vmlinuz root=/dev/sda2 rw rootwait init=/sbin/init console=ttyS0,115200 console=tty0 panic=10 loglevel=4 quiet
}
GRUBEOF

    # Install GRUB for BIOS
    GRUB_MODULES="normal ext2 part_msdos biosdisk fshelp linux serial"

    grub-mkimage -d /usr/lib/grub/i386-pc \
        -o "$TARGET_ROOT/boot/grub/core.img" \
        --format=i386-pc \
        --prefix='(hd0,msdos1)/grub' \
        $GRUB_MODULES 2>/dev/null || true

    mkdir -p "$TARGET_ROOT/boot/grub/i386-pc"
    for mod in $GRUB_MODULES; do
        cp "/usr/lib/grub/i386-pc/${mod}.mod" "$TARGET_ROOT/boot/grub/i386-pc/" 2>/dev/null || true
    done
    cp /usr/lib/grub/i386-pc/{disk.mod,kernelpc.mod,memdisk.mod,tar.mod,search.mod,search_fs_file.mod,search_fs_uuid.mod,search_label.mod} "$TARGET_ROOT/boot/grub/i386-pc/" 2>/dev/null || true

    # Try grub-install first, fallback to manual
    grub-install --target=i386-pc --boot-directory="$TARGET_ROOT/boot" --no-floppy "$SELECTED_DRIVE" 2>/dev/null || {
        cp /usr/lib/grub/i386-pc/boot.img "$TARGET_ROOT/boot/grub/i386-pc/" 2>/dev/null || true
        cp /usr/lib/grub/i386-pc/diskboot.img "$TARGET_ROOT/boot/grub/i386-pc/" 2>/dev/null || true
        cp "$TARGET_ROOT/boot/grub/core.img" "$TARGET_ROOT/boot/grub/i386-pc/" 2>/dev/null || true

        dd if=/usr/lib/grub/i386-pc/boot.img of="$SELECTED_DRIVE" bs=440 count=1 conv=notrunc 2>/dev/null || true
        dd if="$TARGET_ROOT/boot/grub/core.img" of="$SELECTED_DRIVE" bs=512 seek=1 conv=notrunc 2>/dev/null || true

        GRUB_BIOS_SETUP=""
        for path in /usr/lib/grub/i386-pc/grub-bios-setup /usr/libexec/grub-bios-setup grub-bios-setup; do
            if [ -x "$path" ]; then
                GRUB_BIOS_SETUP="$path"
                break
            fi
        done
        if [ -n "$GRUB_BIOS_SETUP" ]; then
            "$GRUB_BIOS_SETUP" -d "$TARGET_ROOT/boot/grub/i386-pc" "$SELECTED_DRIVE" 2>/dev/null || true
        fi
    }

    echo 95

    # --- Sync and unmount ---
    echo 97
    sync
    umount "$TARGET_ROOT/boot"
    umount "$TARGET_ROOT"

    echo 100

} | whiptail --title "Installing Tungsten Core Linux" --gauge "Starting installation..." 15 70 0

# --- Check result ---
if [ $? -eq 0 ]; then
    whiptail --title "Installation Complete" --yesno \
"Tungsten Core Linux has been successfully installed!

System configuration:
  - User: root
  - Password: tungsten
  - Network: DHCP
  - SSH: Enabled

The system will now reboot. Remove the Live CD/USB when prompted.

Reboot now?" 18 60 && reboot
else
    whiptail --title "Installation Failed" --msgbox \
"The installation failed. Please check the logs and try again.\n\nThe target drive may be in an inconsistent state." 10 60
    # Cleanup on failure
    umount "$TARGET_ROOT/boot" 2>/dev/null || true
    umount "$TARGET_ROOT" 2>/dev/null || true
    exit 1
fi
