# IT Nexus Agent - Installer
# Cereda Systems GmbH

$InstallDir = "$env:ProgramData\IT Nexus Agent"
$AgentKey   = "cereda-agent-2024-secure-key"
$ServerUrl  = "https://it-nexus.cereda-systems.de"
$TaskName   = "IT Nexus Agent"

Write-Host "=== IT Nexus Agent Installation ===" -ForegroundColor Cyan

# Verzeichnis erstellen
if (-not (Test-Path $InstallDir)) {
    New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
}

# Dateien kopieren
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Copy-Item "$ScriptDir\it-nexus-agent.ps1" "$InstallDir\it-nexus-agent.ps1" -Force

# Config schreiben
$config = @{ server_url = $ServerUrl; agent_key = $AgentKey } | ConvertTo-Json
Set-Content -Path "$InstallDir\config.json" -Value $config -Force

# Alten Task entfernen falls vorhanden
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue

# Scheduled Task erstellen (laeuft alle 5 Minuten als SYSTEM)
$action  = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File `"$InstallDir\it-nexus-agent.ps1`""
$trigger = New-ScheduledTaskTrigger -RepetitionInterval (New-TimeSpan -Minutes 5) -Once -At (Get-Date)
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -MultipleInstances IgnoreNew -StartWhenAvailable
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest -ErrorAction SilentlyContinue
if (-not $principal) {
    $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -RunLevel Highest
}

Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null

Write-Host "Installiert in: $InstallDir" -ForegroundColor Green
Write-Host "Scheduled Task '$TaskName' erstellt (alle 5 Min)" -ForegroundColor Green
Write-Host "Server: $ServerUrl" -ForegroundColor Green
Write-Host ""
Write-Host "Erster Checkin wird jetzt ausgefuehrt..." -ForegroundColor Yellow
Start-ScheduledTask -TaskName $TaskName
Write-Host "Fertig!" -ForegroundColor Green
