$ErrorActionPreference = "Stop"

$installRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$appRoot = Join-Path $installRoot "app"
$indexPath = Join-Path $appRoot "index.html"
$serverScript = Join-Path $installRoot "server.ps1"
$portFile = Join-Path $installRoot "server-port.txt"

if (!(Test-Path -LiteralPath $indexPath) -or !(Test-Path -LiteralPath $serverScript)) {
  Add-Type -AssemblyName System.Windows.Forms
  [System.Windows.Forms.MessageBox]::Show("Know God More files were not found. Please reinstall the app.", "Know God More", "OK", "Error") | Out-Null
  exit 1
}

function Test-KgmServer {
  param([int]$Port)
  try {
    $request = [System.Net.WebRequest]::Create("http://127.0.0.1:$Port/kgm-health")
    $request.Timeout = 600
    $response = $request.GetResponse()
    $reader = New-Object System.IO.StreamReader($response.GetResponseStream())
    $body = $reader.ReadToEnd()
    $reader.Close()
    $response.Close()
    return $body -eq "Know God More"
  } catch {
    return $false
  }
}

function Start-KgmServer {
  param([int]$Port)
  $powershell = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
  $arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$serverScript`" -Root `"$appRoot`" -Port $Port -InstallRoot `"$installRoot`""
  Start-Process -FilePath $powershell -ArgumentList $arguments -WindowStyle Hidden | Out-Null
  for ($i = 0; $i -lt 30; $i++) {
    Start-Sleep -Milliseconds 180
    if (Test-KgmServer -Port $Port) {
      Set-Content -LiteralPath $portFile -Value $Port -Encoding ASCII
      return $true
    }
  }
  return $false
}

$ports = @(8797, 8798, 8799, 8800, 8801, 8787, 8788, 8789, 8790, 8791)
if (Test-Path -LiteralPath $portFile) {
  $savedPort = [int](Get-Content -LiteralPath $portFile -ErrorAction SilentlyContinue | Select-Object -First 1)
  if ($savedPort -ge 8797 -and $savedPort -le 8801) {
    $ports = @($savedPort) + ($ports | Where-Object { $_ -ne $savedPort })
  }
}

$port = $null
foreach ($candidate in $ports) {
  if (Test-KgmServer -Port $candidate -or (Start-KgmServer -Port $candidate)) {
    $port = $candidate
    break
  }
}

if (!$port) {
  Add-Type -AssemblyName System.Windows.Forms
  [System.Windows.Forms.MessageBox]::Show("Know God More could not start its local certificate server. Please close the app and try again.", "Know God More", "OK", "Error") | Out-Null
  exit 1
}

$appUrl = "http://127.0.0.1:$port/index.html"
$browserCandidates = @(
  "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe",
  "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe",
  "$env:ProgramFiles\Google\Chrome\Application\chrome.exe",
  "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe"
)

$browser = $browserCandidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
if ($browser) {
  Start-Process -FilePath $browser -ArgumentList "--app=$appUrl"
} else {
  Start-Process -FilePath $appUrl
}
