#!/bin/pwsh
. "$PSScriptRoot/../../Common/Scripts/Context.ps1";

function Update-WindowsInstallation([Context] $context)
{
    if (-not $context.GetUACState()) {
        Write-Host "Upgrading Windows";
        Write-Host "Preparing for Windows Update";
        $null = Import-Module PSWindowsUpdate;

        Write-Host "Performing Windows Update";

        try {
            $null = Install-WindowsUpdate -AcceptAll -IgnoreReboot -ErrorAction "SilentlyContinue";
        }
        catch { }

        if ((Get-WURebootStatus -Silent))
        {
            Write-Information "A Reboot is Required!";
            Write-Information "Windows will reboot now and the installation will be continued automatically.";
            $context.Reboot();
            exit;
        }
        elseif (
            ((Get-WindowsUpdate -IgnoreReboot).Count -gt 0) -and
            ((Get-WindowsUpdate -IgnoreReboot).KB -ne "KB2267602"))
        {
            Write-Information "More updates are available. Restarting upgrade routine.";
            $null = Update-WindowsInstallation $context;
            return;
        }
        else
        {
            Write-Information "Upgrading Windows finished successfully!";
            return;
        }
    }
}