param(
  [Parameter(Mandatory = $true)] [string] $BuildDir
)

$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$projectDeclaration = Get-Content -LiteralPath (Join-Path $repo 'CMakeLists.txt') -Raw
if ($projectDeclaration -notmatch 'project\(SmartCut64 VERSION ([0-9]+\.[0-9]+\.[0-9]+) LANGUAGES CXX\)') {
  throw 'Could not determine the SmartCut64 project version from CMakeLists.txt'
}
$version = $Matches[1]
$resolvedBuildDir = (Resolve-Path -LiteralPath $BuildDir).Path
$nsisRoot = Join-Path $resolvedBuildDir '_CPack_Packages\win64\NSIS'
$script = Join-Path $nsisRoot 'project.nsi'
if (-not (Test-Path -LiteralPath $script)) { throw "Missing CPack NSIS script: $script" }

$document = [IO.File]::ReadAllText($script)
if ($document -notmatch 'RequestExecutionLevel (admin|user)') {
  throw 'The CPack NSIS script no longer contains the expected elevation directive'
}
$document = $document.Replace('RequestExecutionLevel admin', 'RequestExecutionLevel user')
$document = $document.Replace('SetShellVarContext all', 'SetShellVarContext current')
$machineUninstallKey = 'HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\SmartCut64'
$userUninstallKey = 'HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\SmartCut64'
$document = $document.Replace($machineUninstallKey, $userUninstallKey)
[IO.File]::WriteAllText($script, $document, [Text.UTF8Encoding]::new($false))

$makensis = Get-Command makensis.exe -ErrorAction SilentlyContinue
$makensisPath = if ($makensis) { $makensis.Source } else {
  $nsisInstall = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\NSIS' -ErrorAction Stop).'(default)'
  Join-Path $nsisInstall 'makensis.exe'
}
if (-not (Test-Path -LiteralPath $makensisPath)) { throw "Missing NSIS compiler: $makensisPath" }
& $makensisPath '/V1' $script
if ($LASTEXITCODE -ne 0) { throw "NSIS failed while rebuilding the per-user installer with $LASTEXITCODE" }

$installer = Join-Path $resolvedBuildDir "SmartCut64-$version-win64.exe"
$generatedInstaller = Join-Path $nsisRoot "SmartCut64-$version-win64.exe"
if (-not (Test-Path -LiteralPath $generatedInstaller)) { throw "Missing rebuilt installer: $generatedInstaller" }
Copy-Item -LiteralPath $generatedInstaller -Destination $installer -Force
Write-Host "Per-user NSIS installer generated: $installer"
