param(
  [string]$Version = "dev",
  [string]$OutDir = "dist-release",
  [switch]$SkipFrontend
)

$ErrorActionPreference = "Stop"
$Root = Resolve-Path (Join-Path $PSScriptRoot "..")
$Out = Join-Path $Root $OutDir

function Run-Step {
  param(
    [string]$WorkingDirectory,
    [string]$FilePath,
    [string[]]$Arguments
  )
  Push-Location $WorkingDirectory
  try {
    & $FilePath @Arguments
    if ($LASTEXITCODE -ne 0) {
      throw "$FilePath $($Arguments -join ' ') failed with exit code $LASTEXITCODE"
    }
  } finally {
    Pop-Location
  }
}

if (-not $SkipFrontend) {
  foreach ($App in @("admin", "portal", "setup")) {
    $WebDir = Join-Path $Root "web\$App"
    if (-not (Test-Path (Join-Path $WebDir "node_modules"))) {
      Run-Step $WebDir "npm" @("install")
    }
    Run-Step $WebDir "npm" @("run", "build")
  }
}

New-Item -ItemType Directory -Force -Path $Out | Out-Null

function Copy-IfExists {
  param(
    [string]$Source,
    [string]$Destination
  )
  if (Test-Path $Source) {
    if (Test-Path $Destination) {
      Remove-Item -Recurse -Force $Destination
    }
    New-Item -ItemType Directory -Force -Path (Split-Path $Destination -Parent) | Out-Null
    Copy-Item -Recurse -Force $Source $Destination
  }
}

$RepoRoot = Resolve-Path (Join-Path $Root "..\..")
$DataUpdatePublic = Join-Path $Out "data\update\public"
$DataUpdateNotice = Join-Path $Out "data\update-notice"
New-Item -ItemType Directory -Force -Path $DataUpdatePublic | Out-Null
Copy-IfExists (Join-Path $RepoRoot "update-notice") $DataUpdateNotice
foreach ($Name in @("update-info.json", "media-types.json", "tool-status.json", "modules.json")) {
  $Source = Join-Path $RepoRoot "server\update\public\$Name"
  if (Test-Path $Source) {
    Copy-Item -Force $Source (Join-Path $DataUpdatePublic $Name)
  }
}
Copy-IfExists (Join-Path $RepoRoot "server\update\public\downloads") (Join-Path $DataUpdatePublic "downloads")

$Targets = @(
  @{ GOOS = "windows"; GOARCH = "amd64"; Name = "ymhut-unified-management-windows-amd64.exe" },
  @{ GOOS = "linux"; GOARCH = "amd64"; Name = "ymhut-unified-management-linux-amd64" },
  @{ GOOS = "linux"; GOARCH = "arm64"; Name = "ymhut-unified-management-linux-arm64" }
)

foreach ($Target in $Targets) {
  $env:GOOS = $Target.GOOS
  $env:GOARCH = $Target.GOARCH
  $env:CGO_ENABLED = "0"
  $Output = Join-Path $Out $Target.Name
  Run-Step $Root "go" @("build", "-tags", "embed_web", "-buildvcs=false", "-trimpath", "-ldflags", "-s -w -X ymhut-box/server/unified-management/internal/config.Version=$Version", "-o", $Output, ".\cmd\unified-management")
}

Remove-Item Env:\GOOS -ErrorAction SilentlyContinue
Remove-Item Env:\GOARCH -ErrorAction SilentlyContinue
Remove-Item Env:\CGO_ENABLED -ErrorAction SilentlyContinue

Write-Host "Built release binaries in $Out"
