$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root

$startedProcesses = @()

function Start-TrackedProcess {
    param(
        [string]$FilePath,
        [string[]]$ArgumentList = @(),
        [string]$WorkingDirectory = $root
    )

    $proc = Start-Process -FilePath $FilePath `
        -ArgumentList $ArgumentList `
        -WorkingDirectory $WorkingDirectory `
        -PassThru

    $script:startedProcesses += $proc
    return $proc
}

function Stop-AllTrackedProcesses {
    Write-Host ""
    Write-Host "Stopping launched processes..."

    foreach ($proc in $script:startedProcesses) {
        try {
            if ($proc -and -not $proc.HasExited) {
                Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
                Write-Host "Stopped PID $($proc.Id)"
            }
        }
        catch {
        }
    }

    try {
        $containerIds = docker ps --filter "ancestor=surrealdb/surrealdb:v2.2.1" --format "{{.ID}}"
        foreach ($id in $containerIds) {
            docker stop $id | Out-Null
            Write-Host "Stopped Docker container $id"
        }
    }
    catch {
    }
}

Register-EngineEvent PowerShell.Exiting -Action {
    Stop-AllTrackedProcesses
} | Out-Null

Write-Host "Building RelayCore..."
dotnet build .\RelayCore\RelayCore.csproj
if ($LASTEXITCODE -ne 0) { throw "RelayCore build failed." }

Write-Host "Building RelayServer..."
dotnet build .\RelayServer\RelayServer.csproj
if ($LASTEXITCODE -ne 0) { throw "RelayServer build failed." }

Write-Host "Building RelayClient (Windows only)..."
dotnet build .\RelayClient\RelayClient.csproj -f net10.0-windows10.0.19041.0
if ($LASTEXITCODE -ne 0) { throw "RelayClient build failed." }

$coreDll = Join-Path $root "RelayCore\bin\Debug\net9.0\RelayCore.dll"
$serverDll = Join-Path $root "RelayServer\bin\Debug\net10.0\RelayServer.dll"
$clientExe = Join-Path $root "RelayClient\bin\Debug\net10.0-windows10.0.19041.0\win-x64\RelayClient.exe"

Write-Host "Starting SurrealDB..."
Start-TrackedProcess `
    -FilePath "docker" `
    -ArgumentList @(
    "run",
    "--rm",
    "-p", "8000:8000",
    "-v", "/mydata:/mydata",
    "surrealdb/surrealdb:v2.2.1",
    "start",
    "--user", "root",
    "--pass", "secret"
)

Start-Sleep -Seconds 5

Write-Host "Starting RelayCore..."
Start-TrackedProcess `
    -FilePath "dotnet" `
    -ArgumentList @($coreDll)

Start-Sleep -Seconds 3

Write-Host "Starting RelayServer..."
Start-TrackedProcess `
    -FilePath "dotnet" `
    -ArgumentList @($serverDll)

Start-Sleep -Seconds 3

Write-Host "Starting RelayClient (Keeper317)..."
Start-TrackedProcess `
    -FilePath $clientExe `
    -ArgumentList @("--user", "Keeper317")

Start-Sleep -Seconds 1

Write-Host "Starting RelayClient (Ru_Kira)..."
Start-TrackedProcess `
    -FilePath $clientExe `
    -ArgumentList @("--user", "Ru_Kira")

Start-Sleep -Seconds 20

Write-Host "Starting RelayClient (Test)..."
Start-TrackedProcess `
    -FilePath $clientExe `
    -ArgumentList @("--user", "Test")

Write-Host "" 
Write-Host "Everything started." 
Write-Host "Press Ctrl+C in this PowerShell to stop everything."

while ($true) {
    Start-Sleep -Seconds 1
}