# IT Nexus Agent — Sofort-Update auf neues EXE (als Admin ausführen)
$newExe  = "$PSScriptRoot\bin\Release\net8.0-windows\IT-Nexus-Agent.exe"
$svcExe  = "C:\ProgramData\IT Nexus Agent\IT-Nexus-Agent.exe"
$pfExe   = "C:\Program Files\IT Nexus Agent\IT-Nexus-Agent.exe"
$svcName = "IT Nexus Agent"

Write-Host "IT Nexus Agent — Update-Script" -ForegroundColor Cyan
Write-Host "Neue EXE: $newExe" -ForegroundColor Gray

if (-not (Test-Path $newExe)) {
    Write-Host "FEHLER: Release-EXE nicht gefunden. Erst bauen!" -ForegroundColor Red
    Read-Host; exit 1
}

# 1. Tray/Dashboard-Prozesse beenden
Write-Host "1. Stoppe Dashboard-Prozesse..." -ForegroundColor Yellow
Get-Process -Name "IT-Nexus-Agent" -ErrorAction SilentlyContinue | Stop-Process -Force
Start-Sleep -Milliseconds 800

# 2. Service stoppen
Write-Host "2. Stoppe Windows Service..." -ForegroundColor Yellow
net stop $svcName 2>$null
Start-Sleep -Seconds 2

# 3. EXE an beiden Orten ersetzen
Write-Host "3. Kopiere neue EXE..." -ForegroundColor Yellow
$deps = @("IT-Nexus-Agent.dll","IT-Nexus-Agent.runtimeconfig.json",
          "IT-Nexus-Agent.deps.json","Newtonsoft.Json.dll",
          "System.Management.dll","System.ServiceProcess.ServiceController.dll")

foreach ($dest in @($svcExe, $pfExe)) {
    if (Test-Path (Split-Path $dest)) {
        Copy-Item $newExe $dest -Force
        foreach ($d in $deps) {
            $src = Join-Path (Split-Path $newExe) $d
            if (Test-Path $src) { Copy-Item $src (Split-Path $dest) -Force }
        }
        Write-Host "   OK: $dest" -ForegroundColor Green
    }
}

# 4. Service-Binary-Pfad aktualisieren (falls nötig)
$regPath = (sc.exe qc $svcName 2>$null | Select-String "BINARY_PATH").ToString().Trim()
Write-Host "4. Aktueller Service-Pfad: $regPath" -ForegroundColor Gray

# Wenn Service auf ProgramData zeigt → auf Program Files umlenken
if ($regPath -like "*ProgramData*") {
    Write-Host "   Migriere Service-Pfad zu Program Files..." -ForegroundColor Yellow
    sc.exe delete $svcName 2>$null
    Start-Sleep -Milliseconds 500
    sc.exe create $svcName binPath= "`"$pfExe`"" start= auto DisplayName= "IT Nexus Agent" 2>$null
    sc.exe description $svcName "Cereda Systems IT Nexus Monitoring Agent" 2>$null
    sc.exe failure $svcName reset= 60 actions= restart/5000/restart/10000/restart/30000 2>$null
}

# 5. Service starten
Write-Host "5. Starte Windows Service..." -ForegroundColor Yellow
net start $svcName 2>$null
Start-Sleep -Seconds 3

$svc = Get-Service -Name $svcName -ErrorAction SilentlyContinue
if ($svc.Status -eq "Running") {
    Write-Host ""
    Write-Host "Update erfolgreich! Service laeuft." -ForegroundColor Green
    Write-Host "Naechster Check-in in max. 60 Sekunden." -ForegroundColor Gray
} else {
    Write-Host "WARNUNG: Service nicht gestartet. Status: $($svc.Status)" -ForegroundColor Red
}

Write-Host ""
Write-Host "Druecke Enter zum Schliessen..."
Read-Host
