param(
  [Parameter(Mandatory = $true)][string]$ProjectRoot,
  [Parameter(Mandatory = $true)][string]$WorkerPath,
  [Parameter(Mandatory = $true)][string]$JobsFile,
  [Parameter(Mandatory = $true)][string]$SessionDir
)

$ErrorActionPreference = "Stop"

if (-not (Test-Path -LiteralPath $SessionDir)) {
  New-Item -ItemType Directory -Path $SessionDir -Force | Out-Null
}

$node = (Get-Command node.exe -ErrorAction Stop).Source
$stdout = Join-Path $SessionDir "launcher-worker.stdout.log"
$stderr = Join-Path $SessionDir "launcher-worker.stderr.log"
$pidFile = Join-Path $SessionDir "worker.pid"

$process = Start-Process `
  -FilePath $node `
  -ArgumentList @($WorkerPath, $JobsFile, $SessionDir) `
  -WorkingDirectory $ProjectRoot `
  -WindowStyle Hidden `
  -RedirectStandardOutput $stdout `
  -RedirectStandardError $stderr `
  -PassThru

Set-Content -LiteralPath $pidFile -Value $process.Id -Encoding UTF8
Write-Output $process.Id
