#!/usr/bin/env bash
# Cross-build Windows NSIS installer on Linux (requires mingw-w64, rust target x86_64-pc-windows-gnu).
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$REPO_ROOT"

if ! command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
  echo "Install mingw: apt-get install -y mingw-w64"
  exit 1
fi

rustup target add x86_64-pc-windows-gnu
if [[ -f package-lock.json ]]; then npm ci 2>/dev/null || npm install; else npm install; fi
npm run build

VERSION="$(node -p "require('./package.json').version")"

# The nsis bundle dir accumulates every previous build's *-setup.exe and is
# NEVER cleaned by `tauri build` (it only adds/overwrites the one matching the
# current version's filename). A stale-artifact bug here previously caused
# `find ... | head -1` (below) to silently pick up an OLD version's exe --
# `find`'s output order is filesystem/inode order, NOT mtime order, so this
# is not just theoretical: it happened for real across the 1.3.2/1.3.3/1.3.4
# releases, which all ended up shipping the byte-identical 1.3.2 binary.
# Removing the whole bundle dir before building guarantees the only
# *-setup.exe present afterward is the one just built for THIS version.
rm -rf "$REPO_ROOT/src-tauri/target/x86_64-pc-windows-gnu/release/bundle/nsis"

npm run tauri -- build --target x86_64-pc-windows-gnu

SETUP=$(find "$REPO_ROOT/src-tauri/target/x86_64-pc-windows-gnu/release/bundle/nsis" -name '*-setup.exe' 2>/dev/null | head -1)
if [[ -z "$SETUP" || ! -f "$SETUP" ]]; then
  echo "NSIS setup.exe not found after build"
  exit 1
fi

OUT="$REPO_ROOT/vigthoria-workbench-${VERSION}-x64-setup.exe"
cp -f "$SETUP" "$OUT"
echo "Built: $OUT"
ls -la "$OUT"
