<#
.SYNOPSIS
    Updates an existing GLPI Agent installation (x64 only) using a local HTTP repository.
.DESCRIPTION
    Checks the currently installed GLPI Agent version and updates it to the latest one
    specified in the 'latest_version.txt' file on the local server if a newer version is found.
#>
param (
    [string]$setupOptions = '/quiet RUNNOW=1 SERVER=https://glpi.mh-itsm.de/ ADD_FIREWALL_EXCEPTION=1 ADDLOCAL=feat_AGENT,feat_DEPLOY EXECMODE=1',
    [string]$allowVerbose = "Yes"
)

$versionUrl = "https://repository.mh-itsm.de/windows/latest_version.txt"
$baseUrl = "https://repository.mh-itsm.de/windows/GLPI-Agent-"

# Zufällige Verzögerung von 5 bis 30 Minuten
$minDelay = 5     # Minimale Verzögerung in Minuten
$maxDelay = 30    # Maximale Verzögerung in Minuten

# Zufällige Minuten berechnen
$randomMinutes = Get-Random -Minimum $minDelay -Maximum ($maxDelay + 1)
$delaySeconds = $randomMinutes * 60

Write-Output "Warte $randomMinutes Minuten ($delaySeconds Sekunden)..."
Start-Sleep -Seconds $delaySeconds


function Get-InstalledVersion {
    $regPaths = @(
        "HKLM:\SOFTWARE\GLPI-Agent\Installer",
        "HKLM:\SOFTWARE\Wow6432Node\GLPI-Agent\Installer"
    )
    foreach ($path in $regPaths) {
        try {
            $ver = (Get-ItemProperty -Path $path -Name "Version" -ErrorAction SilentlyContinue).Version
            if ($ver) { return $ver }
        } catch { }
    }
    return $null
}

function Get-LatestGLPIAgentInfo {
    $web = New-Object System.Net.WebClient
    $web.Headers.Add("User-Agent", "PowerShell")
    try {
        Write-Verbose "Fetching latest version from $versionUrl ..." -Verbose
        $latestVersion = $web.DownloadString($versionUrl).Trim()
        
        if ($latestVersion -match '^\d+([\.\d+])*$') {
            $downloadUrl = $baseUrl + "$latestVersion" + "-x64.msi"

            Write-Verbose "Discovered latest version: $latestVersion" -Verbose
            return @($latestVersion, $downloadUrl)
        } else {
            Write-Verbose "Error: Retrieved data '$latestVersion' is not a valid version string." -Verbose
        }
    } catch {
        Write-Verbose "Error fetching latest version from index file ($versionUrl): $_" -Verbose
    } finally {
        $web.Dispose()
    }
    return $null
}

function Invoke-UpdateGLPIAgent {
    param (
        [string]$downloadUrl,
        [string]$version,
        [string]$setupOptions
    )

    $tempFile = Join-Path $env:TEMP "GLPI-Agent-$version-x64.msi"
    Write-Verbose "Downloading $downloadUrl ..." -Verbose
    $web = New-Object System.Net.WebClient
    try {
        $web.DownloadFile($downloadUrl, $tempFile)
        Write-Verbose "Running update for GLPI Agent $version ..." -Verbose
        $proc = Start-Process -FilePath "msiexec.exe" -ArgumentList "/i `"$tempFile`" $setupOptions" -Wait -PassThru -NoNewWindow
        if ($proc.ExitCode -eq 0) {
            Write-Verbose "Update completed successfully." -Verbose
        } else {
            Write-Verbose "Update failed with code $($proc.ExitCode)." -Verbose
        }
    } finally {
        $web.Dispose()
        if (Test-Path $tempFile) {
            Remove-Item $tempFile -Force -ErrorAction SilentlyContinue
        }
    }
}

if ($allowVerbose -ne "No") { Write-Verbose "Checking for GLPI Agent updates..." -Verbose }

$currentVersion = Get-InstalledVersion
if (-not $currentVersion) {
    Write-Verbose "GLPI Agent not found or version unknown. Skipping update." -Verbose
    exit 0
}

$info = Get-LatestGLPIAgentInfo
if (-not $info) {
    Write-Verbose "Could not retrieve latest release info. Exiting." -Verbose
    exit 1
}

$latestVersion = $info[0]
$downloadUrl   = $info[1]

Write-Verbose "Installed version: $currentVersion" -Verbose
Write-Verbose "Latest version:    $latestVersion" -Verbose

try {
    $currentVerObj = [version]$currentVersion
    $latestVerObj = [version]$latestVersion
    
    if ($currentVerObj -lt $latestVerObj) {
        Write-Verbose "New version available ($latestVersion is newer than $currentVersion). Updating..." -Verbose
        Invoke-UpdateGLPIAgent -downloadUrl $downloadUrl -version $latestVersion -setupOptions $setupOptions
    } else {
        Write-Verbose "GLPI Agent is already up to date." -Verbose
    }
} catch {
    Write-Verbose "Error comparing versions using [version] type. Assuming up-to-date." -Verbose
}