param(
  [string]$Version = $(Get-Content VERSION -ErrorAction SilentlyContinue),
  [string]$SourceDir = (Get-Location).Path,
  [string]$OutputDir = (Join-Path (Get-Location).Path "release"),
  [string]$Iscc = "ISCC.exe"
)

$ErrorActionPreference = "Stop"

if ([string]::IsNullOrWhiteSpace($Version)) {
  $Version = "0.1.0-dev"
}

$exe = Join-Path $SourceDir "bin\anothereditor.exe"
if (!(Test-Path $exe)) {
  throw "Application binary not found: $exe"
}

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

function Invoke-SignTool([string]$Path) {
  $signtool = $env:WINDOWS_SIGNTOOL
  if ([string]::IsNullOrWhiteSpace($signtool)) {
    $signtool = "signtool.exe"
  }
  $timestamp = $env:WINDOWS_SIGN_TIMESTAMP_URL
  if ([string]::IsNullOrWhiteSpace($timestamp)) {
    $timestamp = "http://timestamp.digicert.com"
  }
  if (![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_CERT_SHA1)) {
    & $signtool sign /fd SHA256 /tr $timestamp /td SHA256 /sha1 $env:WINDOWS_SIGN_CERT_SHA1 $Path
    return
  }
  if (![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_PFX)) {
    $args = @("sign", "/fd", "SHA256", "/tr", $timestamp, "/td", "SHA256", "/f", $env:WINDOWS_SIGN_PFX)
    if (![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_PFX_PASSWORD)) {
      $args += @("/p", $env:WINDOWS_SIGN_PFX_PASSWORD)
    }
    $args += $Path
    & $signtool @args
  }
}

if (![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_CERT_SHA1) -or ![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_PFX)) {
  Invoke-SignTool $exe
}

$template = Get-Content (Join-Path $SourceDir "packaging\windows\anothereditor.iss.in") -Raw
$iss = Join-Path $OutputDir "anothereditor.iss"
$template = $template.Replace("@VERSION@", $Version)
$template = $template.Replace("@SOURCE_DIR@", $SourceDir)
$template = $template.Replace("@OUTPUT_DIR@", $OutputDir)
Set-Content -Path $iss -Value $template -Encoding UTF8

& $Iscc $iss

$installer = Get-ChildItem $OutputDir -Filter "AnotherEditor-Setup-*.exe" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if ($installer -and (![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_CERT_SHA1) -or ![string]::IsNullOrWhiteSpace($env:WINDOWS_SIGN_PFX))) {
  Invoke-SignTool $installer.FullName
}

if ($installer) {
  $zip = Join-Path $OutputDir "AnotherEditor-windows-x86_64.zip"
  if (Test-Path $zip) {
    Remove-Item $zip -Force
  }
  $stage = Join-Path $OutputDir "AnotherEditor-windows-x86_64"
  if (Test-Path $stage) {
    Remove-Item $stage -Recurse -Force
  }
  New-Item -ItemType Directory -Force -Path $stage | Out-Null
  Copy-Item $installer.FullName -Destination $stage
  Copy-Item (Join-Path $SourceDir "README.md") -Destination $stage
  Copy-Item (Join-Path $SourceDir "LICENSE") -Destination $stage
  Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zip -Force
  Remove-Item $stage -Recurse -Force
  Write-Host "Built $($installer.FullName)"
  Write-Host "Wrote $zip"
}
