#!/usr/bin/env bash
#
# Proxmox VE installer launcher for Hetzner Rescue System
# Starts the official Proxmox ISO through QEMU with direct disk access.
#
# This script does NOT partition or format disks.
# Disk installation is performed manually in the Proxmox installer.
#

set -Eeuo pipefail

# ---------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------

ISO_BASE="https://enterprise.proxmox.com/iso"
WORKDIR="/root"
VNC_PORT=5900
QEMU_MEMORY="16G"
VARS_FILE="/root/OVMF_VARS_4M-pve-install.fd"

# ---------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------

error() {
    echo
    echo "[ERROR] $*" >&2
    exit 1
}

info() {
    echo "[INFO] $*"
}

warn() {
    echo "[WARNING] $*"
}

section() {
    echo
    echo "============================================================"
    echo " $*"
    echo "============================================================"
}

pause() {
    read -rp "Press ENTER to continue..."
}

# ---------------------------------------------------------------------
# 1. Root check
# ---------------------------------------------------------------------

section "Checking permissions"

[[ $EUID -eq 0 ]] || error "Run this script as root."

info "Running as root."

# ---------------------------------------------------------------------
# 2. Check KVM
# ---------------------------------------------------------------------

section "Checking hardware virtualization"

[[ -e /dev/kvm ]] || error \
    "KVM is not available. Check virtualization support in BIOS."

info "KVM device found: /dev/kvm"

# ---------------------------------------------------------------------
# 3. Detect boot mode
# ---------------------------------------------------------------------

section "Detecting boot mode"

if [[ -d /sys/firmware/efi ]]; then
    BOOT_MODE="UEFI"
else
    BOOT_MODE="LEGACY"
fi

info "Detected boot mode: $BOOT_MODE"

# ---------------------------------------------------------------------
# 4. Install required packages
# ---------------------------------------------------------------------

section "Installing required packages"

apt-get update

DEBIAN_FRONTEND=noninteractive apt-get install -y \
    qemu-system-x86 \
    ovmf \
    curl \
    wget \
    ca-certificates

command -v qemu-system-x86_64 >/dev/null ||
    error "QEMU installation failed."

info "Required packages installed."

# ---------------------------------------------------------------------
# 5. Detect network interface and MAC address
# ---------------------------------------------------------------------

section "Detecting network interface"

IFACE=$(
    ip -4 route show default |
    awk 'NR == 1 {
        for (i = 1; i <= NF; i++) {
            if ($i == "dev") {
                print $(i + 1)
                exit
            }
        }
    }'
)

[[ -n "$IFACE" ]] || error "Could not detect network interface."

[[ -e "/sys/class/net/$IFACE/address" ]] ||
    error "Network interface $IFACE does not exist."

MYMAC=$(cat "/sys/class/net/$IFACE/address")

info "Network interface : $IFACE"
info "MAC address       : $MYMAC"

# ---------------------------------------------------------------------
# 6. Show physical disks
# ---------------------------------------------------------------------

section "Available physical disks"

lsblk -d -o NAME,SIZE,MODEL,SERIAL,ROTA,TRAN

echo
info "Available persistent disk identifiers:"
echo

for disk in /dev/disk/by-id/ata-* /dev/disk/by-id/wwn-*; do
    [[ -L "$disk" ]] || continue

    REALDISK=$(readlink -f "$disk")

    [[ -b "$REALDISK" ]] || continue
    [[ "$(lsblk -dn -o TYPE "$REALDISK")" == "disk" ]] || continue

    printf "  %-65s -> %s\n" "$disk" "$REALDISK"
done

echo
warn "Select the two physical HDDs that will become your ZFS mirror."
warn "All existing data on these disks will be destroyed by installation."

echo

read -rp "First disk (/dev/disk/by-id/...): " DISK1
read -rp "Second disk (/dev/disk/by-id/...): " DISK2

# ---------------------------------------------------------------------
# 7. Validate disk selection
# ---------------------------------------------------------------------

section "Validating selected disks"

for disk in "$DISK1" "$DISK2"; do
    [[ -b "$disk" ]] || error "Disk does not exist: $disk"

    TYPE=$(lsblk -dn -o TYPE "$disk")

    [[ "$TYPE" == "disk" ]] ||
        error "$disk is not a physical disk."

    MOUNTS=$(lsblk -nrpo MOUNTPOINT "$disk")

    if [[ -n "$MOUNTS" ]]; then
        error "$disk or one of its partitions is mounted. Unmount it first."
    fi
done

REALDISK1=$(readlink -f "$DISK1")
REALDISK2=$(readlink -f "$DISK2")

[[ "$REALDISK1" != "$REALDISK2" ]] ||
    error "You selected the same physical disk twice."

echo
echo "Selected disks:"
echo "  Disk 1: $DISK1"
echo "  Disk 2: $DISK2"
echo

lsblk -o NAME,SIZE,MODEL,SERIAL "$REALDISK1" "$REALDISK2"

echo
warn "Verify that these are the correct two 10 TB Enterprise HDDs."

read -rp "Are these disks correct? Type YES to continue: " CONFIRM

[[ "$CONFIRM" == "YES" ]] ||
    error "Disk selection cancelled."

# ---------------------------------------------------------------------
# 8. Check existing RAID configuration
# ---------------------------------------------------------------------

section "Checking existing RAID configuration"

if [[ -f /proc/mdstat ]]; then
    cat /proc/mdstat
fi

echo
warn "The selected disks must not belong to an active mdadm array."

read -rp "Continue after checking RAID configuration? [y/N]: " CONFIRM

[[ "$CONFIRM" =~ ^[Yy]$ ]] ||
    error "Installation preparation cancelled."

# ---------------------------------------------------------------------
# 9. Download latest Proxmox ISO
# ---------------------------------------------------------------------

section "Downloading Proxmox VE ISO"

cd "$WORKDIR"

ISO=$(
    curl -fsSL "$ISO_BASE/" |
    grep -oE 'proxmox-ve_[0-9]+(\.[0-9]+)*-[0-9]+\.iso' |
    sort -V |
    tail -n 1
)

[[ -n "$ISO" ]] || error "Could not determine latest Proxmox ISO."

ISO_PATH="$WORKDIR/$ISO"

info "Selected ISO: $ISO"

if [[ -f "$ISO_PATH" ]]; then
    info "ISO already exists. Reusing existing file."
else
    wget -O "$ISO_PATH" "$ISO_BASE/$ISO"
fi

[[ -s "$ISO_PATH" ]] || error "ISO download failed."

info "ISO ready: $ISO_PATH"

ls -lh "$ISO_PATH"

# ---------------------------------------------------------------------
# 10. Prepare UEFI firmware
# ---------------------------------------------------------------------

section "Preparing firmware"

QEMU_FIRMWARE=()

if [[ "$BOOT_MODE" == "UEFI" ]]; then

    OVMF_CODE="/usr/share/OVMF/OVMF_CODE_4M.fd"
    OVMF_VARS="/usr/share/OVMF/OVMF_VARS_4M.fd"

    [[ -f "$OVMF_CODE" ]] ||
        error "OVMF CODE firmware not found: $OVMF_CODE"

    [[ -f "$OVMF_VARS" ]] ||
        error "OVMF VARS firmware not found: $OVMF_VARS"

    if [[ -f "$VARS_FILE" ]]; then
        warn "An existing VARS file was found: $VARS_FILE"

        read -rp "Reuse it? [y/N]: " REUSE

        if [[ ! "$REUSE" =~ ^[Yy]$ ]]; then
            cp "$OVMF_VARS" "$VARS_FILE"
            info "Created fresh UEFI VARS file."
        else
            info "Reusing existing UEFI VARS file."
        fi
    else
        cp "$OVMF_VARS" "$VARS_FILE"
        info "Created UEFI VARS file."
    fi

    chmod 600 "$VARS_FILE"

    QEMU_FIRMWARE+=(
        -drive "if=pflash,format=raw,unit=0,readonly=on,file=$OVMF_CODE"
        -drive "if=pflash,format=raw,unit=1,file=$VARS_FILE"
    )

else
    info "Legacy BIOS detected. No OVMF firmware required."
fi

# ---------------------------------------------------------------------
# 11. Show connection information
# ---------------------------------------------------------------------

section "VNC connection information"

echo
echo "Open a NEW PowerShell window on your local computer."
echo
echo "SSH tunnel:"
echo
echo "  ssh -L $VNC_PORT:127.0.0.1:$VNC_PORT root@YOUR_SERVER_IP"
echo
echo "Then connect using your VNC client:"
echo
echo "  127.0.0.1:$VNC_PORT"
echo
echo "Make sure the SSH tunnel remains open."
echo

read -rp "Is the SSH tunnel ready? [y/N]: " CONFIRM

[[ "$CONFIRM" =~ ^[Yy]$ ]] ||
    error "Start the SSH tunnel before launching QEMU."

# ---------------------------------------------------------------------
# 12. Final confirmation
# ---------------------------------------------------------------------

section "QEMU configuration"

echo "Boot mode       : $BOOT_MODE"
echo "Memory          : $QEMU_MEMORY"
echo "ISO             : $ISO_PATH"
echo "Network         : $IFACE"
echo "MAC address     : $MYMAC"
echo "VNC             : 127.0.0.1:$VNC_PORT"
echo
echo "Disk 1          : $DISK1"
echo "Disk 2          : $DISK2"
echo

warn "QEMU will receive direct access to both physical disks."
warn "The Proxmox installer can erase their contents."

read -rp "Start QEMU now? Type YES to continue: " CONFIRM

[[ "$CONFIRM" == "YES" ]] ||
    error "QEMU startup cancelled."

# ---------------------------------------------------------------------
# 13. Start QEMU
# ---------------------------------------------------------------------

section "Starting Proxmox VE installer"

info "Starting QEMU..."
info "Use your VNC client to access the installer."
echo
info "Press Ctrl+C to stop QEMU."

exec qemu-system-x86_64 \
    -enable-kvm \
    -cpu host \
    -m "$QEMU_MEMORY" \
    -boot d \
    -cdrom "$ISO_PATH" \
    -drive "file=$DISK1,format=raw,if=virtio" \
    -drive "file=$DISK2,format=raw,if=virtio" \
    -nic none \
    -netdev user,id=n0 \
    -device virtio-net-pci,netdev=n0,mac="$MYMAC" \
    "${QEMU_FIRMWARE[@]}" \
    -vnc "127.0.0.1:0"


