# ========================================
# Build-HDGL-LiveISO.ps1
# Windows HDGL Live ISO Builder
# ========================================

# -------------------------------
# Config
# -------------------------------
$IsoUrl = "https://download.proxmox.com/iso/proxmox-ve-9.0-iso-installer.iso"
$WorkDir = "$env:TEMP\HDGL_LiveISO"
$MountDir = "$WorkDir\Mount"
$ExtractDir = "$WorkDir\Extract"
$EFI_Bin = "$WorkDir\hdgl_live_boot.efi"
$OutputISO = "$env:USERPROFILE\Desktop\HDGL_Live.iso"

# Ensure directories
New-Item -ItemType Directory -Force -Path $MountDir, $ExtractDir

# -------------------------------
# Download ISO
# -------------------------------
Write-Host "Downloading ISO..."
$IsoPath = "$WorkDir\original.iso"
Invoke-WebRequest -Uri $IsoUrl -OutFile $IsoPath

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

# -------------------------------
# Extract ISO contents
# -------------------------------
Write-Host "Copying ISO contents..."
Copy-Item "$DriveLetter\*" $ExtractDir -Recurse -Force

# -------------------------------
# Unmount ISO
# -------------------------------
Dismount-DiskImage -ImagePath $IsoPath

# -------------------------------
# Copy HDGL EFI Bootloader
# -------------------------------
Write-Host "Injecting HDGL EFI Bootloader..."
$EFI_BootPath = Join-Path $ExtractDir "EFI\BOOT"
New-Item -ItemType Directory -Force -Path $EFI_BootPath
Copy-Item $EFI_Bin $EFI_BootPath\BOOTX64.EFI -Force

# -------------------------------
# Create new bootable ISO
# -------------------------------
Write-Host "Creating bootable ISO..."
$oscdimg = "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\oscdimg.exe"
if (-Not (Test-Path $oscdimg)) { throw "oscdimg.exe not found. Install Windows ADK." }

$BootSector = "$ExtractDir\boot\etfsboot.com"
Start-Process -Wait -FilePath $oscdimg -ArgumentList @(
    "-b$BootSector",
    "-u2",
    "-udfver102",
    "-lHDGL_Live",
    "$ExtractDir",
    "$OutputISO"
)

Write-Host "HDGL Live ISO created at $OutputISO"
