<#
.SYNOPSIS
Build a live HDGL-bootable ISO for Debian/Proxmox with our HDGL EFI bootloader.
#>

param(
    [string]$SourceISO = "C:\ISOs\proxmox-ve-9.0.iso",
    [string]$WorkDir   = "C:\HDGL_Build",
    [string]$OutputISO = "C:\HDGL_Live.iso",
    [string]$BootLoader = "C:\HDGL_Boot\hdgl_live_boot.efi"
)

# -------------------------------
# 1. Prepare workspace
# -------------------------------
Write-Host "Preparing workspace..."
if (Test-Path $WorkDir) { Remove-Item $WorkDir -Recurse -Force }
New-Item -ItemType Directory -Path $WorkDir

# Mount ISO
Write-Host "Mounting source ISO..."
$MountResult = Mount-DiskImage -ImagePath $SourceISO -PassThru
$DriveLetter = ($MountResult | Get-Volume).DriveLetter + ":"

# Copy contents to workspace
Write-Host "Copying ISO contents..."
Copy-Item "$DriveLetter\*" -Destination $WorkDir -Recurse

# Dismount ISO
Dismount-DiskImage -ImagePath $SourceISO

# -------------------------------
# 2. Inject HDGL EFI bootloader
# -------------------------------
Write-Host "Injecting HDGL EFI bootloader..."
$EFIPath = Join-Path $WorkDir "EFI\BOOT"
if (!(Test-Path $EFIPath)) { New-Item -ItemType Directory -Path $EFIPath -Force }

Copy-Item $BootLoader -Destination (Join-Path $EFIPath "BOOTX64.EFI") -Force

# Optional: rename existing EFI loader as backup
$OriginalEFI = Join-Path $EFIPath "grubx64.efi"
if (Test-Path $OriginalEFI) {
    Rename-Item $OriginalEFI "grubx64_backup.efi"
}

# -------------------------------
# 3. Prepare boot catalog for ISO
# -------------------------------
Write-Host "Creating ISO boot catalog..."
$ISOCmd = @(
    "-o `"$OutputISO`"",
    "-b EFI\BOOT\BOOTX64.EFI",
    "-no-emul-boot",
    "-iso-level 3",
    "-udf",
    "-J",
    "-R",
    "`"$WorkDir`""
) -join " "

# Use mkisofs or genisoimage if installed; fallback to oscdimg
if (Get-Command mkisofs -ErrorAction SilentlyContinue) {
    mkisofs $ISOCmd
} elseif (Get-Command oscdimg -ErrorAction SilentlyContinue) {
    oscdimg -n -m -bEFI\BOOT\BOOTX64.EFI $WorkDir $OutputISO
} else {
    Write-Error "No ISO building utility found (mkisofs or oscdimg required)."
    exit 1
}

Write-Host "HDGL Live ISO built successfully at $OutputISO"
