#Requires -RunAsAdministrator
<#
.SYNOPSIS
    Downloads and silently installs .NET Framework 4.8 if not already present.
#>
param(
    [int]$MinRelease = 528040,
    [string]$DownloadUrl = 'https://go.microsoft.com/fwlink/?linkid=2088631',
    [string]$WorkDir = $env:TEMP
)

$ErrorActionPreference = 'Stop'

function Test-DotNet48Installed {
    param([int]$ReleaseMin)
    $key = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
    if (-not (Test-Path $key)) { return $false }
    $release = (Get-ItemProperty -Path $key -ErrorAction SilentlyContinue).Release
    return ($release -ge $ReleaseMin)
}

function Invoke-DotNetInstaller {
    param(
        [string]$InstallerPath,
        [string[]]$Arguments
    )
    Write-Host "Running: $InstallerPath $($Arguments -join ' ')"
    $proc = Start-Process -FilePath $InstallerPath -ArgumentList $Arguments -Wait -PassThru -NoNewWindow
    return $proc.ExitCode
}

Write-Host '=== K_Recycle: .NET Framework 4.8 Setup ==='

if (Test-DotNet48Installed -ReleaseMin $MinRelease) {
    Write-Host '.NET Framework 4.8 (or newer) is already installed.'
    exit 0
}

if (-not (Test-Path $WorkDir)) {
    New-Item -ItemType Directory -Path $WorkDir -Force | Out-Null
}

$installerPath = Join-Path $WorkDir 'ndp48-x86-x64-allos-enu.exe'
$logPath = Join-Path $WorkDir 'DotNet48-Install.log'

Write-Host 'Downloading .NET Framework 4.8 offline installer from Microsoft...'
Write-Host "URL: $DownloadUrl"
Invoke-WebRequest -Uri $DownloadUrl -OutFile $installerPath -UseBasicParsing

Write-Host 'Installing .NET Framework 4.8 (silent)...'
$exitCode = Invoke-DotNetInstaller -InstallerPath $installerPath -Arguments @(
    '/q',
    '/norestart',
    '/log',
    $logPath
)

# 0=OK, 3010/1641=success but restart required
if ($exitCode -notin 0, 3010, 1641) {
    Write-Warning "Quiet install returned $exitCode. Retrying with /passive ..."
    $exitCode = Invoke-DotNetInstaller -InstallerPath $installerPath -Arguments @(
        '/passive',
        '/norestart',
        '/log',
        $logPath
    )
}

if ($exitCode -notin 0, 3010, 1641) {
    Write-Error ".NET Framework 4.8 installation failed. Exit code: $exitCode. Log: $logPath"
}

Start-Sleep -Seconds 5

if (-not (Test-DotNet48Installed -ReleaseMin $MinRelease)) {
    Write-Error '.NET Framework 4.8 installation finished but version check failed. A system restart may be required.'
}

Write-Host '.NET Framework 4.8 installed successfully.'
if ($exitCode -in 3010, 1641) {
    Write-Host 'Note: A system restart is recommended to complete .NET installation.'
    exit 3010
}

exit 0
