# Uninstall-ProjectRelayServer.ps1
# Must be run as Administrator.
# This script assumes it lives inside the ProjectRelay install folder.

Write-Host "=== ProjectRelay Server – Uninstaller (Scheduled Task) ==="
Write-Host ""

# ---- Admin check ----
$principal = New-Object Security.Principal.WindowsPrincipal `
    [Security.Principal.WindowsIdentity]::GetCurrent()

if (-not $principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
    Write-Host "This script must be run as Administrator." -ForegroundColor Red
    Write-Host "Right-click this file and choose 'Run as administrator'."
    exit 1
}

# ---- Settings ----
$taskName   = "ProjectRelayServer"
$installDir = $PSScriptRoot
$exeName    = "ProjectRelayServer.exe"

Write-Host "Task Name : $taskName"
Write-Host "Install Dir: $installDir"
Write-Host ""

# ---- Confirm ----
$confirm = Read-Host "This will remove ProjectRelay Server from: $installDir  (Y/N)"
if ($confirm -notin @('Y','y')) {
    Write-Host "Cancelled."
    exit 0
}

# ---- End & delete scheduled task (if it exists) ----
Write-Host "Checking for scheduled task '$taskName'..."
$taskExists = $false
try {
    schtasks.exe /Query /TN $taskName | Out-Null
    $taskExists = $true
} catch {
    $taskExists = $false
}

if ($taskExists) {
    Write-Host "Ending scheduled task (if running)..."
    try {
        schtasks.exe /End /TN $taskName | Out-Null
        Start-Sleep -Seconds 1
        Write-Host "Task ended (or was not running)."
    } catch {
        Write-Host "WARN: Could not end task (it may not be running)." -ForegroundColor Yellow
    }

    Write-Host "Deleting scheduled task..."
    try {
        schtasks.exe /Delete /TN $taskName /F | Out-Null
        Write-Host "Task deleted."
    } catch {
        Write-Host "ERROR: Could not delete the scheduled task." -ForegroundColor Red
    }
} else {
    Write-Host "Scheduled task not found. (Nothing to stop/delete.)" -ForegroundColor Yellow
}

# ---- Kill any running EXE process (best effort) ----
Write-Host "Checking for running process '$exeName'..."
try {
    $procName = [System.IO.Path]::GetFileNameWithoutExtension($exeName)
    $procs = Get-Process -Name $procName -ErrorAction SilentlyContinue
    if ($procs) {
        Write-Host "Stopping running process(es)..."
        $procs | Stop-Process -Force -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 1
        Write-Host "Process(es) stopped."
    } else {
        Write-Host "No running process found."
    }
} catch {
    Write-Host "WARN: Could not stop process (may not exist)." -ForegroundColor Yellow
}

# ---- Self-delete / remove install folder ----
# We can't delete the script while it's running, so we generate a temp cleanup script that runs after this exits.
Write-Host "Preparing to remove install folder..."

$tempCleanup = Join-Path $env:TEMP ("ProjectRelay_Cleanup_" + [guid]::NewGuid().ToString("N") + ".ps1")

$cleanupScript = @"
Start-Sleep -Seconds 2

`$target = "$installDir"

# Try a few times in case something still has a handle open
for (`$i = 0; `$i -lt 10; `$i++) {
  try {
    if (Test-Path -LiteralPath `$target) {
      Remove-Item -LiteralPath `$target -Recurse -Force -ErrorAction Stop
    }
    break
  } catch {
    Start-Sleep -Seconds 1
  }
}

# Delete this cleanup script
try {
  Remove-Item -LiteralPath "$tempCleanup" -Force -ErrorAction SilentlyContinue
} catch { }
"@

Set-Content -LiteralPath $tempCleanup -Value $cleanupScript -Encoding UTF8

Write-Host "Launching cleanup..."
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$tempCleanup`"" -WindowStyle Hidden | Out-Null

Write-Host ""
Write-Host "=== Uninstall initiated. ==="
Write-Host "The install folder will be removed in a few seconds:"
Write-Host "  $installDir"
Write-Host ""
Write-Host "You may close this window."
