param(
  [string]$HustVisualPath = "tmp/hustvisual-v1/build/local"
)

$ErrorActionPreference = "Stop"

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "../..")).Path
$sourceDir = (Resolve-Path $HustVisualPath).Path
$buildDir = Join-Path $repoRoot "tmp/asset-build"
$assetDir = Join-Path $repoRoot "assets"
$pathSeparator = [IO.Path]::PathSeparator
$previousTexInputs = $env:TEXINPUTS
$locationPushed = $false

New-Item -ItemType Directory -Force $buildDir, $assetDir | Out-Null

try {
  $env:TEXINPUTS = "$sourceDir//$pathSeparator$previousTexInputs"
  Push-Location $repoRoot
  $locationPushed = $true

  $jobs = @(
    @{
      Name = "hust-emblem-color"
      Source = "tools/assets/hust-emblem-color.tex"
    },
    @{
      Name = "hust-emblem-white"
      Source = "tools/assets/hust-emblem-white.tex"
      # White artwork is invisible to Ghostscript's automatic bounding-box
      # detector. This matches the standard-color emblem geometry.
      BBox = "-1 723 90 792"
    },
    @{
      Name = "hust-name-blue"
      Source = "tools/assets/hust-name-blue.tex"
    },
    @{
      Name = "hust-name-white"
      Source = "tools/assets/hust-name-white.tex"
      # White artwork is invisible to Ghostscript's automatic bounding-box
      # detector. This is the same geometry reported for the blue wordmark.
      BBox = "0 740 255 792"
    }
  )

  foreach ($job in $jobs) {
    $rawName = "$($job.Name)-raw"
    & xelatex `
      -file-line-error `
      -halt-on-error `
      -interaction=nonstopmode `
      "-jobname=$rawName" `
      "-output-directory=$buildDir" `
      $job.Source
    if ($LASTEXITCODE -ne 0) {
      throw "xelatex failed while building $($job.Name)"
    }

    if ($job.BBox) {
      & pdfcrop `
        --bbox $job.BBox `
        "tmp/asset-build/$rawName.pdf" `
        "assets/$($job.Name).pdf"
    }
    else {
      & pdfcrop `
        --margins 0 `
        "tmp/asset-build/$rawName.pdf" `
        "assets/$($job.Name).pdf"
    }
    if ($LASTEXITCODE -ne 0) {
      throw "pdfcrop failed while building $($job.Name)"
    }
  }
}
finally {
  if ($locationPushed) {
    Pop-Location
  }
  $env:TEXINPUTS = $previousTexInputs
}
