#Requires -RunAsAdministrator

# Post-deployment verification script.
# Checks that all deployment steps completed correctly.
# Outputs a pass/fail report.

$ErrorActionPreference = "Continue"

$PassCount = 0
$FailCount = 0
$WarnCount = 0

function Test-Check {
    param(
        [string]$Name,
        [scriptblock]$Check,
        [switch]$WarnOnly
    )
    try {
        $result = & $Check
        if ($result) {
            Write-Host "  [PASS] $Name" -ForegroundColor Green
            $script:PassCount++
        } else {
            if ($WarnOnly) {
                Write-Host "  [WARN] $Name" -ForegroundColor Yellow
                $script:WarnCount++
            } else {
                Write-Host "  [FAIL] $Name" -ForegroundColor Red
                $script:FailCount++
            }
        }
    }
    catch {
        Write-Host "  [FAIL] $Name (exception: $_)" -ForegroundColor Red
        $script:FailCount++
    }
}

function Get-RegValue {
    param([string]$Path, [string]$Name)
    try {
        return (Get-ItemProperty -Path $Path -Name $Name -ErrorAction Stop).$Name
    }
    catch { return $null }
}

Write-Host ""
Write-Host "========================================"
Write-Host "  Deployment Verification"
Write-Host "  Computer: $env:COMPUTERNAME"
Write-Host "  Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
Write-Host "========================================"

# -----------------------------------------------------------------------
# Log file
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- Log ---"
Test-Check "Deploy.log exists" {
    Test-Path "C:\Windows\Setup\Scripts\Deploy.log"
}

# -----------------------------------------------------------------------
# Admin account
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- Admin account ---"
Test-Check "Account adminx9 exists" {
    Get-LocalUser -Name "adminx9" -ErrorAction SilentlyContinue
}
Test-Check "Account adminx9 is enabled" {
    (Get-LocalUser -Name "adminx9" -ErrorAction SilentlyContinue).Enabled -eq $true
}
Test-Check "Account adminx9 in Administrators" {
    $adminsGroup = (Get-LocalGroup | Where-Object { $_.SID -eq "S-1-5-32-544" }).Name
    Get-LocalGroupMember -Group $adminsGroup -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -like "*adminx9" }
}
Test-Check "Account adminx9 hidden from login screen" {
    $specialPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"
    (Get-ItemProperty -Path $specialPath -Name "adminx9" -ErrorAction SilentlyContinue).adminx9 -eq 0
}

# -----------------------------------------------------------------------
# Activation
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- Activation ---"
Test-Check "Windows activated" {
    $status = (Get-CimInstance SoftwareLicensingProduct -Filter "PartialProductKey IS NOT NULL AND Name LIKE 'Windows%'" -ErrorAction SilentlyContinue |
               Select-Object -First 1).LicenseStatus
    $status -eq 1
} -WarnOnly

# -----------------------------------------------------------------------
# Software
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- Software ---"
Test-Check "7-Zip installed" {
    (Test-Path "${env:ProgramFiles}\7-Zip\7z.exe") -or
    (Test-Path "${env:ProgramFiles(x86)}\7-Zip\7z.exe")
}

Test-Check "Adobe Acrobat installed" {
    (Test-Path "$env:ProgramFiles\Adobe\Acrobat DC\Acrobat\Acrobat.exe") -or
    (Test-Path "${env:ProgramFiles(x86)}\Adobe\Acrobat DC\Acrobat\Acrobat.exe") -or
    (Test-Path "${env:ProgramFiles(x86)}\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe") -or
    (Test-Path "$env:ProgramFiles\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe")
}

Test-Check "OpenVPN Connect installed" {
    (Test-Path "$env:ProgramFiles\OpenVPN Connect\OpenVPNConnect.exe") -or
    (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" `
        -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like "OpenVPN*" })
} -WarnOnly

Test-Check "Atera agent installed" {
    (Test-Path "$env:ProgramFiles\ATERA Networks\AteraAgent\AteraAgent.exe") -or
    (Test-Path "${env:ProgramFiles(x86)}\ATERA Networks\AteraAgent\AteraAgent.exe")
} -WarnOnly

# -----------------------------------------------------------------------
# PDF default
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- PDF default ---"
Test-Check "HKCR .pdf set to AcroExch" {
    if (-not (Get-PSDrive -Name HKCR -ErrorAction SilentlyContinue)) {
        New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null
    }
    $val = (Get-ItemProperty -Path "HKCR:\.pdf" -Name "(Default)" -ErrorAction SilentlyContinue)."(Default)"
    $val -eq "AcroExch.Document.DC"
} -WarnOnly

# -----------------------------------------------------------------------
# Bloatware
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- Bloatware removal ---"

$bloatwareToCheck = @(
    "Microsoft.549981C3F5F10"   # Cortana
    "Microsoft.BingNews"
    "MicrosoftTeams"
    "Microsoft.XboxApp"
    "Microsoft.YourPhone"
    "Microsoft.ZuneMusic"
    "Microsoft.GamingApp"
)

foreach ($pkg in $bloatwareToCheck) {
    Test-Check "Removed: $pkg" {
        $installed = Get-AppxPackage -Name $pkg -AllUsers -ErrorAction SilentlyContinue
        -not $installed
    } -WarnOnly
}

Test-Check "Calculator kept" {
    Get-AppxPackage -Name "Microsoft.WindowsCalculator" -AllUsers -ErrorAction SilentlyContinue
}

# -----------------------------------------------------------------------
# System registry (HKLM)
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- System registry ---"

Test-Check "BypassNRO set" {
    (Get-RegValue "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\OOBE" "BypassNRO") -eq 1
}

Test-Check "Teams auto-install disabled" {
    (Get-RegValue "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Communications" "ConfigureChatAutoInstall") -eq 0
}

Test-Check "Widgets disabled" {
    (Get-RegValue "HKLM:\SOFTWARE\Policies\Microsoft\Dsh" "AllowNewsAndInterests") -eq 0
}

Test-Check "Edge First Run hidden" {
    (Get-RegValue "HKLM:\SOFTWARE\Policies\Microsoft\Edge" "HideFirstRunExperience") -eq 1
}

Test-Check "GameDVR disabled" {
    (Get-RegValue "HKLM:\SOFTWARE\Policies\Microsoft\Windows\GameDVR" "AllowGameDVR") -eq 0
}

Test-Check "Time zone set" {
    (Get-TimeZone).Id -eq "Central Europe Standard Time"
}

Test-Check "Standby timeout AC = 0 (never)" {
    $val = & powercfg /query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE 2>&1 | Select-String "Current AC Power Setting Index"
    $val -match "0x00000000"
} -WarnOnly

Test-Check "WPAD proxy disabled" {
    (Get-RegValue "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" "AutoDetect") -eq 0
} -WarnOnly

# -----------------------------------------------------------------------
# Current user (HKCU) - profile + personalization
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- User settings (current user) ---"

Test-Check "Dark system theme" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" "SystemUsesLightTheme") -eq 0
}

Test-Check "Light app theme" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" "AppsUseLightTheme") -eq 1
}

Test-Check "Transparency disabled" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" "EnableTransparency") -eq 0
}

Test-Check "Taskbar aligned left" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" "TaskbarAl") -eq 0
} -WarnOnly

Test-Check "File extensions visible" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" "HideFileExt") -eq 0
}

Test-Check "Explorer opens to This PC" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" "LaunchTo") -eq 1
}

Test-Check "This PC icon on desktop" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" "{20D04FE0-3AEA-1069-A2D8-08002B30309D}") -eq 0
}

Test-Check "Start menu Recommended hidden" {
    (Get-RegValue "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer" "HideRecommendedSection") -eq 1
}

Test-Check "Start menu recently added hidden" {
    (Get-RegValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" "Start_TrackProgs") -eq 0
}

# -----------------------------------------------------------------------
# BackInfo
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- BackInfo ---"

Test-Check "BackInfo.exe deployed" {
    Test-Path "C:\Program Files\Backinfo\BackInfo.exe"
}

Test-Check "BackInfo startup shortcut" {
    Test-Path "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\BackInfo.lnk"
}

Test-Check "BackInfo OSName registry" {
    (Get-RegValue "HKLM:\SOFTWARE\BackInfo" "OSName") -ne $null
}

# -----------------------------------------------------------------------
# Network
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- Network ---"

Test-Check "Network profile Private" {
    $profiles = Get-NetConnectionProfile -ErrorAction SilentlyContinue
    -not ($profiles | Where-Object { $_.NetworkCategory -ne "Private" })
} -WarnOnly

# -----------------------------------------------------------------------
# C:\X9 directory
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "--- PC identity ---"

Test-Check "C:\\X9 directory exists" {
    Test-Path "C:\X9"
}

Test-Check "C:\\X9 has custom icon" {
    Test-Path "C:\X9\desktop.ini"
} -WarnOnly

# -----------------------------------------------------------------------
# Summary
# -----------------------------------------------------------------------
Write-Host ""
Write-Host "========================================"
Write-Host "  PASS: $PassCount  FAIL: $FailCount  WARN: $WarnCount"
Write-Host "========================================"

if ($FailCount -gt 0) {
    Write-Host "Deployment verification FAILED. Review items above." -ForegroundColor Red
    exit 1
} else {
    Write-Host "Deployment verification PASSED." -ForegroundColor Green
    exit 0
}
