#Requires -RunAsAdministrator

$ServiceName  = "MailPrint"
$DisplayName  = "MailPrint - E-Mail & WebAPI zu Drucker"
$Description  = "Druckt PDF-Anhaenge automatisch aus E-Mails (IMAP/POP3) und per REST API auf Windows-Drucker."
$ExePath      = Join-Path $PSScriptRoot "publish\MailPrint.exe"

if (-not (Test-Path $ExePath)) {
    Write-Error "MailPrint.exe nicht gefunden: $ExePath"
    exit 1
}

$existing = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if ($existing) {
    Write-Host "Dienst '$ServiceName' ist bereits installiert. Stoppe zuerst..." -ForegroundColor Yellow
    Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 2
}

Write-Host "Installiere Dienst '$ServiceName'..." -ForegroundColor Cyan

New-Service `
    -Name        $ServiceName `
    -DisplayName $DisplayName `
    -Description $Description `
    -BinaryPathName $ExePath `
    -StartupType Automatic | Out-Null

sc.exe failure $ServiceName reset= 3600 actions= restart/5000/restart/10000/restart/30000 | Out-Null

Write-Host "Starte Dienst..." -ForegroundColor Cyan
Start-Service -Name $ServiceName

$svc = Get-Service -Name $ServiceName
Write-Host ""
Write-Host "Ergebnis:" -ForegroundColor Green
Write-Host "  Name:   $($svc.Name)"
Write-Host "  Status: $($svc.Status)"
Write-Host "  Start:  $($svc.StartType)"
Write-Host ""
Write-Host "Fertig. MailPrint laeuft jetzt als Windows-Dienst." -ForegroundColor Green
Write-Host "Logs: $(Join-Path $PSScriptRoot 'publish\logs')"
