# ================================
# Fleet Windows 11 Upgrade Script
# ================================

$logFile = "C:\Temp\Win11Upgrade.log"
$dir = "C:\Temp"
New-Item -ItemType Directory -Path $dir -Force | Out-Null

function Write-Log {
    param ([string]$msg)
    $time = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
    "$time - $msg" | Out-File -FilePath $logFile -Append -Encoding utf8
    Write-Host $msg
}

Write-Log "===== Starting Upgrade Script ====="

# Get OS info (fast)
$os = Get-CimInstance Win32_OperatingSystem
$build = [int]$os.BuildNumber
Write-Log "OS: $($os.Caption)"
Write-Log "Build: $build"

# Check if upgrade is needed
$targetBuild = 26000
if ($os.Caption -like "*Windows 11*" -and $build -ge $targetBuild) {
    Write-Log "Already on latest Windows 11. Exiting."
    exit 0
}

Write-Log "Upgrade required. Proceeding..."

# Enable unsupported hardware bypass (safe if not needed)
Write-Log "Setting compatibility bypass registry key"
reg add HKLM\SYSTEM\Setup\MoSetup /v AllowUpgradesWithUnsupportedTPMOrCPU /t REG_DWORD /d 1 /f | Out-Null

# Download Installation Assistant
$url = "https://go.microsoft.com/fwlink/?linkid=2171764"
$file = "$dir\Win11Upgrade.exe"

Write-Log "Downloading Windows 11 Installation Assistant..."
try {
    Invoke-WebRequest $url -OutFile $file -UseBasicParsing -ErrorAction Stop
} catch {
    Write-Log "Download failed: $($_.Exception.Message)"
    exit 1
}

if (!(Test-Path $file)) {
    Write-Log "Download file not found. Exiting."
    exit 1
}

Write-Log "Download complete"

# Kill any previous upgrade processes
Get-Process -ErrorAction SilentlyContinue |
    Where-Object { $_.Name -like "*Windows10UpgraderApp*" } |
    Stop-Process -Force -ErrorAction SilentlyContinue

# Run upgrade silently
Write-Log "Starting upgrade process (this will take 30-60+ minutes)..."
$args = "/quietinstall /skipeula /auto upgrade /copylogs $dir"
$proc = Start-Process $file -ArgumentList $args -Wait -PassThru

Write-Log "Upgrade process exited with code: $($proc.ExitCode)"

if ($proc.ExitCode -eq 0) {
    Write-Log "Upgrade succeeded. Machine will reboot automatically."
} else {
    Write-Log "Upgrade may have failed. Check $dir for logs."
}

Write-Log "===== Script Complete ====="
