# Ensures proper display of Czech characters in the console (handles "Handle is invalid" error)
try {
    # Attempt to set the console and PowerShell encoding
    $OutputEncoding = [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
} catch {
    # If running in a non-interactive mode (without a window), setting the console will fail.
    # In this case, we'll set the PowerShell internal variable and proceed.
    $OutputEncoding = [System.Text.Encoding]::UTF8
}

# Define the path to the current script for reliable sub-script calls
$ScriptRoot = Split-Path $MyInvocation.MyCommand.Path

# Path to TightVNC server (edit if you have a different version/path)
$VncServerPath = "C:\Program Files\TightVNC\tvnserver.exe"

# 1. Check for Admin privileges
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "Script must be run as Administrator."
    exit 5
}

# 2. Determine UWF status
try {
    $UwfObject = Get-CimInstance -Namespace "root\standardcimv2\embedded" -ClassName UWF_Filter -ErrorAction Stop
    $IsUwfEnabled = $UwfObject.CurrentEnabled
} catch {
    # If the command fails (e.g., older Windows), display an error
    Write-Warning "Failed to determine status via Get-UwfFilter. Is the UWF feature installed?"
    $IsUwfEnabled = $false
}

Write-Host "UWF filter status: $(if($IsUwfEnabled){'ENABLED'}else{'DISABLED'})" -ForegroundColor Cyan

if ($IsUwfEnabled) {
    Write-Host "UWF is active. Initiating unlock process..." -ForegroundColor Yellow
   
    # 1. Disable UWF (changes take effect after restart)
    uwfmgr.exe filter disable | Out-Null
    Write-Host "UWF filter has been disabled for the next startup." -ForegroundColor Yellow

    Write-Host "Restarting PC..." -ForegroundColor Red
    shutdown.exe /r /t 3 /f

    # 3. Return exit_code 0
    # Return 0 (indicating successful initiation of restart and continuation)
    exit 0
}
