param(
  [Parameter(Mandatory = $true)]
  [string]$AppDir,

  [Parameter(Mandatory = $true)]
  [string]$OutputExe,

  [Parameter(Mandatory = $true)]
  [string]$Version
)

$ErrorActionPreference = "Stop"

function Find-Makensis() {
  $command = Get-Command makensis -ErrorAction SilentlyContinue
  if ($command) {
    return $command.Source
  }

  $searchRoots = @(
    "${env:ProgramFiles(x86)}\NSIS\makensis.exe",
    "${env:ProgramFiles}\NSIS\makensis.exe"
  )

  foreach ($candidate in $searchRoots) {
    if (Test-Path $candidate) {
      return $candidate
    }
  }

  throw "Could not find makensis. Install NSIS 3.x on the Windows build agent."
}

$rootDir = Split-Path -Parent $PSScriptRoot
$nsiPath = Join-Path $rootDir "packaging/windows/farmcontrol-server.nsi"
$installerInclude = Join-Path $rootDir "packaging/windows/installer.nsh"
$workDir = Join-Path $env:TEMP "farmcontrol-server-nsis"

if (Test-Path $workDir) {
  Remove-Item $workDir -Recurse -Force
}
New-Item -ItemType Directory -Path $workDir | Out-Null

$appDirPath = (Resolve-Path -LiteralPath $AppDir).Path

Copy-Item -LiteralPath $nsiPath -Destination (Join-Path $workDir "farmcontrol-server.nsi")
Copy-Item -LiteralPath $installerInclude -Destination (Join-Path $workDir "installer.nsh")

$makensis = Find-Makensis
$outputExePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputExe)
$outputDir = Split-Path $outputExePath -Parent
if (-not (Test-Path $outputDir)) {
  New-Item -ItemType Directory -Path $outputDir | Out-Null
}

$iconPath = Join-Path $rootDir "assets\icon.ico"
$makensisArgs = @(
  "/NOCD"
  "/DOUTFILE=$outputExePath"
  "/DVERSION=$Version"
  "/DAPP_SOURCE_DIR=$appDirPath"
)

if (Test-Path $iconPath) {
  $makensisArgs += "/DINSTALLER_ICON=$iconPath"
}

$makensisArgs += (Join-Path $workDir "farmcontrol-server.nsi")

Push-Location $workDir
try {
  & $makensis @makensisArgs
} finally {
  Pop-Location
}

if (-not (Test-Path $outputExePath)) {
  throw "NSIS installer was not created at $outputExePath"
}

Write-Host "Created NSIS installer at $outputExePath"
