Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

param(
    [string]$AppVersion,
    [string]$GoToolchain = 'auto',
    [string]$Arch = 'amd64',
    [string]$InnoSetupCompiler
)

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Split-Path -Parent $scriptDir

if (-not $AppVersion) {
    $AppVersion = (Get-Content -Path (Join-Path $repoRoot 'VERSION.txt') -Raw).Trim()
}

if ($Arch -ne 'amd64') {
    throw "Unsupported Arch '$Arch'. Only amd64 is wired into the current installer flow."
}

$stageDir = Join-Path $scriptDir 'build\stage'
$outputDir = Join-Path $scriptDir 'build\installer'
$cacheDir = Join-Path $scriptDir 'build\cache'
$guiExePath = Join-Path $stageDir 'MirageGUI.exe'
$cliExePath = Join-Path $stageDir 'mirage.exe'
$issPath = Join-Path $scriptDir 'MirageSetup.iss'
$winresDir = Join-Path $scriptDir 'winres'
$winresTemplatePath = Join-Path $winresDir 'winres.json'
$generatedWinresPath = Join-Path $stageDir 'winres.generated.json'
$sysoPath = Join-Path $repoRoot "cmd\mirage\rsrc_windows_$Arch.syso"

New-Item -ItemType Directory -Force -Path $stageDir | Out-Null
New-Item -ItemType Directory -Force -Path $outputDir | Out-Null
New-Item -ItemType Directory -Force -Path $cacheDir | Out-Null

$winres = Get-Content -Path $winresTemplatePath -Raw | ConvertFrom-Json
$winres.RT_MANIFEST.'#1'.'0804'.identity.version = $AppVersion
$winres.RT_VERSION.'#1'.'0000'.fixed.file_version = $AppVersion
$winres.RT_VERSION.'#1'.'0000'.fixed.product_version = $AppVersion
$winres.RT_VERSION.'#1'.'0000'.info.'0804'.FileVersion = $AppVersion
$winres.RT_VERSION.'#1'.'0000'.info.'0804'.ProductVersion = $AppVersion
$json = $winres | ConvertTo-Json -Depth 100
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($generatedWinresPath, $json, $utf8NoBom)

Push-Location $repoRoot
try {
    $env:GOTOOLCHAIN = $GoToolchain
    go run ./cmd/mkwinpayload $Arch $stageDir $cacheDir
    go run ./cmd/mkwinres $Arch $generatedWinresPath $winresDir $sysoPath

    $env:GOOS = 'windows'
    $env:GOARCH = $Arch
    go build -trimpath -ldflags='-H=windowsgui -s -w' -o $guiExePath ./cmd/mirage
    go build -trimpath -ldflags='-s -w' -o $cliExePath ./cmd/tailscale
} finally {
    Pop-Location
}

if (-not $InnoSetupCompiler) {
    $compiler = Get-Command ISCC.exe -ErrorAction SilentlyContinue
    if ($compiler) {
        $InnoSetupCompiler = $compiler.Source
    } else {
        $defaultCompiler = Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6\ISCC.exe'
        if (Test-Path $defaultCompiler) {
            $InnoSetupCompiler = $defaultCompiler
        } else {
            throw 'ISCC.exe not found. Install Inno Setup 6 or pass -InnoSetupCompiler.'
        }
    }
}

& $InnoSetupCompiler "/DAppVersion=$AppVersion" "/DStageDir=$stageDir" "/DRepoRoot=$repoRoot" "/DOutputDir=$outputDir" $issPath
