<#
    Restart-ProjectRelayServer.ps1
    - Restarts the ProjectRelay server in the most robust way possible.
    - If the scheduled task does not exist, it will be created automatically
      (assuming ProjectRelayServer.exe is in the same folder as this script).
#>

param(
    # Name of the scheduled task to control
    [string]$TaskName = 'ProjectRelayServer',

    # Optional explicit path to the server EXE; if blank, we'll assume it's
    # ProjectRelayServer.exe in the same folder as this script.
    [string]$ExePath  = ''
)

$ErrorActionPreference = 'Stop'

# Resolve default EXE path if not supplied
if ([string]::IsNullOrWhiteSpace($ExePath)) {
    $ExePath = Join-Path -Path $PSScriptRoot -ChildPath 'ProjectRelayServer.exe'
}

Write-Host "Restarting ProjectRelay server using task '$TaskName'..." -ForegroundColor Cyan
Write-Host "Expected server executable: $ExePath" -ForegroundColor DarkGray

# Helper: ensure the scheduled task exists; if not, create it
function Ensure-ProjectRelayTask {
    param(
        [string]$TaskName,
        [string]$ExePath
    )

    # Try to get existing task
    $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
    if ($task) {
        return $task
    }

    Write-Warning "Scheduled task '$TaskName' not found. Attempting to create it..."

    if (-not (Test-Path -LiteralPath $ExePath)) {
        throw "Cannot create scheduled task: server executable not found at '$ExePath'."
    }

    $action    = New-ScheduledTaskAction -Execute $ExePath
    $trigger   = New-ScheduledTaskTrigger -AtStartup
    $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -RunLevel Highest
    $settings  = New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)

    try {
        Register-ScheduledTask `
            -TaskName  $TaskName `
            -Action    $action `
            -Trigger   $trigger `
            -Principal $principal `
            -Settings  $settings `
            -Description 'ProjectRelay photo upload server' | Out-Null

        Write-Host "Scheduled task '$TaskName' created successfully." -ForegroundColor Green
    }
    catch {
        # If it says it already exists, just grab it again
        if ($_.Exception.HResult -eq -2147024713) {  # 0x800700b7
            Write-Warning "Task '$TaskName' appears to already exist; retrieving existing task..."
        }
        else {
            throw $_
        }
    }

    $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction Stop
    return $task
}

try {
    # 1. Make sure the scheduled task exists (create if needed)
    $task = Ensure-ProjectRelayTask -TaskName $TaskName -ExePath $ExePath
    $actualName = $task.TaskName

    # 2. Stop the scheduled task if it is running
    if ($task.State -eq 'Running') {
        Write-Host "Stopping task '$actualName'..." -ForegroundColor DarkCyan
        Stop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue
    }
    else {
        Write-Host "Task '$actualName' is not currently marked as Running." -ForegroundColor DarkGray
    }

    # 3. Kill any leftover ProjectRelayServer.exe processes
    $procName = 'ProjectRelayServer'
    $procs = Get-Process -Name $procName -ErrorAction SilentlyContinue

    if ($procs) {
        foreach ($p in $procs) {
            Write-Host "Killing leftover process $($p.Name) (Id=$($p.Id))..." -ForegroundColor DarkYellow
            $p | Stop-Process -Force
        }
    }
    else {
        Write-Host "No existing $procName processes found." -ForegroundColor DarkGray
    }

    Start-Sleep -Seconds 2

    # 4. Start the scheduled task again (runs as SYSTEM, hidden)
    Write-Host "Starting task '$actualName'..." -ForegroundColor DarkCyan
    Start-ScheduledTask -InputObject $task -ErrorAction Stop

    Write-Host "ProjectRelay server restarted successfully via task '$actualName'." -ForegroundColor Green
}
catch {
    Write-Error "Failed to restart ProjectRelay server: $_"
    exit 1
}
