# Stage offline release folder for USB copy + Install.cmd / SirayaPrinterSetup.exe.
param(
  [string]$Version = "3.0.0",
  [string]$Arch = "win-x64"
)

$ErrorActionPreference = "Stop"
$Root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$ReleaseDir = Join-Path $Root "dist\release"
$PayloadDir = Join-Path $ReleaseDir "payload\$Arch"

. (Join-Path $PSScriptRoot "Build-Payload.ps1")

Build-WindowsPayload -Root $Root -PayloadDir $PayloadDir -Version $Version -Arch $Arch

New-Item -ItemType Directory -Path $ReleaseDir -Force | Out-Null
Copy-Item (Join-Path $PSScriptRoot "Install.cmd") (Join-Path $ReleaseDir "Install.cmd") -Force

function Copy-PowerShellScript {
  param([string]$Source, [string]$Destination)
  $content = Get-Content -Path $Source -Raw -Encoding UTF8
  $utf8Bom = New-Object System.Text.UTF8Encoding $true
  [System.IO.File]::WriteAllText($Destination, $content, $utf8Bom)
}

Copy-PowerShellScript `
  -Source (Join-Path $PSScriptRoot "install-from-folder.ps1") `
  -Destination (Join-Path $ReleaseDir "install-from-folder.ps1")

# Linux USB entry (full linux payload: npm run build:release:linux on Ubuntu)
Copy-Item (Join-Path $Root "installer\linux\install.sh") (Join-Path $ReleaseDir "install.sh") -Force -ErrorAction SilentlyContinue
Copy-Item (Join-Path $Root "installer\linux\install-from-folder.sh") (Join-Path $ReleaseDir "install-from-folder.sh") -Force -ErrorAction SilentlyContinue
if (-not (Test-Path (Join-Path $ReleaseDir "install.sh"))) {
  @'
#!/bin/sh
echo "On Windows use Install.cmd. On Ubuntu build linux payload: npm run build:release:linux"
exit 1
'@ | Set-Content (Join-Path $ReleaseDir "install.sh") -Encoding UTF8
}
Copy-Item (Join-Path $ReleaseDir "install.sh") (Join-Path $ReleaseDir "setup.sh") -Force

$manifest = @{
  version = $Version
  arch    = $Arch
  builtAt = (Get-Date).ToUniversalTime().ToString("o")
  gitSha  = $(if ($env:GITHUB_SHA) { $env:GITHUB_SHA } else { "" })
  entry   = @{
    windows     = "Install.cmd"
    windowsInno = "SirayaPrinterSetup.exe"
    other       = "install.sh"
  }
  payload = "payload/$Arch"
  installTarget = "$env:ProgramFiles\Siraya\Printer"
  uiUrl = "http://127.0.0.1:5000"
} | ConvertTo-Json -Depth 4
$manifest | Set-Content (Join-Path $ReleaseDir "manifest.json") -Encoding UTF8

Write-Host "Release folder ready at $ReleaseDir"
Write-Host "  USB install: copy folder, double-click Install.cmd"
Write-Host "  Optional: npm run build:setup (SirayaPrinterSetup.exe)"
