param(
    [string]$EmmaHome = 'C:\Emma\current',
    [string]$TaskName = 'EmmaLocal'
)

$ErrorActionPreference = 'Stop'

$serverScript = Join-Path $EmmaHome 'provisioning\Start-EmmaServer.ps1'
$agentExe = Join-Path $EmmaHome 'runtime\emma-agent.exe'

if (-not (Test-Path $agentExe)) {
    throw "emma-agent.exe nicht gefunden: $agentExe"
}
if (-not (Test-Path $serverScript)) {
    throw "Start-EmmaServer.ps1 nicht gefunden: $serverScript"
}

function Remove-LegacyEmmaService {
    param(
        [string]$Name,
        [string]$InstallHome
    )

    $existing = Get-Service -Name $Name -ErrorAction SilentlyContinue
    if (-not $existing) {
        return
    }

    if ($existing.Status -eq 'Running') {
        Stop-Service -Name $Name -Force
    }

    $legacyNssm = Join-Path $InstallHome 'runtime\nssm.exe'
    if (Test-Path $legacyNssm) {
        & $legacyNssm remove $Name confirm | Out-Null
    } else {
        & sc.exe delete $Name | Out-Null
    }
}

Remove-LegacyEmmaService -Name $TaskName -InstallHome $EmmaHome
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue | Out-Null

$action = New-ScheduledTaskAction -Execute 'powershell.exe' `
    -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$serverScript`" -EmmaHome `"$EmmaHome`""
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -ExecutionTimeLimit ([TimeSpan]::Zero) `
    -RestartCount 999 `
    -RestartInterval (New-TimeSpan -Minutes 1) `
    -StartWhenAvailable

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

Start-ScheduledTask -TaskName $TaskName
Write-Host "Startup-Task $TaskName registriert und gestartet."
