#Requires -RunAsAdministrator
<#
.SYNOPSIS
    RMM Windows Agent Installer
.EXAMPLE
    .\install.ps1 -BackendURL "https://192.168.85.13:8443" -APIKey "abc123" -AgentName "PC-Muster"
#>
param(
    [Parameter(Mandatory=$true)]  [string]$BackendURL,
    [Parameter(Mandatory=$true)]  [string]$APIKey,
    [Parameter(Mandatory=$false)] [string]$AgentName = $env:COMPUTERNAME,
    [Parameter(Mandatory=$false)] [switch]$Uninstall
)

$InstallDir  = "C:\Program Files\RMMAgent"
$BinaryName  = "rmm-agent-windows.exe"
$ServiceName = "RMMAgent"
$ConfigFile  = "$InstallDir\config.yaml"

if ($Uninstall) {
    Write-Host "Deinstalliere $ServiceName..."
    if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) {
        Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue
        & "$InstallDir\$BinaryName" -uninstall
    }
    Remove-Item -Path $InstallDir -Recurse -Force -ErrorAction SilentlyContinue
    Write-Host "Deinstallation abgeschlossen."
    exit 0
}

# Verzeichnis anlegen
Write-Host "Erstelle Installationsverzeichnis: $InstallDir"
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null

# Binary kopieren (muss im gleichen Ordner wie das Install-Script liegen)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$SourceBinary = Join-Path $ScriptDir $BinaryName

if (-not (Test-Path $SourceBinary)) {
    Write-Error "Binary nicht gefunden: $SourceBinary"
    exit 1
}

Write-Host "Kopiere Binary nach $InstallDir..."
Copy-Item -Path $SourceBinary -Destination "$InstallDir\$BinaryName" -Force

# Konfiguration erstellen
Write-Host "Erstelle Konfiguration..."
$Config = @"
backend_url: "$BackendURL"
api_key: "$APIKey"
agent_name: "$AgentName"
interval_seconds: 60
insecure: true
"@
$Config | Out-File -FilePath $ConfigFile -Encoding UTF8 -Force

# Dienst installieren
Write-Host "Installiere Windows-Dienst..."
if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) {
    Write-Host "Dienst vorhanden — stoppe und entferne alten Dienst..."
    Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue
    & "$InstallDir\$BinaryName" -uninstall
    Start-Sleep -Seconds 2
}

& "$InstallDir\$BinaryName" -config $ConfigFile -install
if ($LASTEXITCODE -ne 0) {
    Write-Error "Dienst-Installation fehlgeschlagen"
    exit 1
}

# Dienst starten
Write-Host "Starte Dienst..."
Start-Service -Name $ServiceName
Start-Sleep -Seconds 2

$svc = Get-Service -Name $ServiceName
Write-Host "Dienst-Status: $($svc.Status)"

if ($svc.Status -eq "Running") {
    Write-Host "`nInstallation erfolgreich!" -ForegroundColor Green
    Write-Host "Log: $InstallDir\rmm-agent.log"
} else {
    Write-Warning "Dienst laeuft nicht — bitte Log pruefen: $InstallDir\rmm-agent.log"
}
