#!/usr/bin/env bash
# Cross-compile the foundation shell for Windows x86_64 with MinGW.
# posprint uses this route and states that BlueGit has no Windows runner.
# This script packages the .exe in a zip. It does not run the Windows binary.
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
version="$(bash "$root/scripts/ci/package-version.sh")"
export CARGO_HOME="${CARGO_HOME:-$root/cargo-home}"
export PATH="$CARGO_HOME/bin:$PATH"

if ! command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
  echo "x86_64-w64-mingw32-gcc is not installed" >&2
  exit 1
fi
rustup target add x86_64-pc-windows-gnu
cargo build --release --locked --target x86_64-pc-windows-gnu --manifest-path "$root/Cargo.toml"

exe="$root/target/x86_64-pc-windows-gnu/release/paperdoll-renderer.exe"
if [[ ! -s "$exe" ]]; then
  echo "Windows executable was not produced" >&2
  exit 1
fi
# PE magic. Refuse to zip an ELF if the linker targeted the wrong OS.
if ! od -An -tx1 -N 2 "$exe" | grep -q "4d 5a"; then
  echo "paperdoll-renderer.exe does not start with MZ" >&2
  exit 1
fi

stage="$(mktemp -d)"
trap 'rm -rf "$stage"' EXIT
install -m 644 "$exe" "$stage/paperdoll-renderer.exe"
install -m 644 "$root/LICENSE" "$stage/LICENSE.txt"
printf '%s\n' "Paperdoll Renderer ${version}" "Foundation shell. Import and render are not included." \
  > "$stage/README.txt"

mkdir -p "$root/dist"
rm -f "$root/dist/paperdoll-renderer-${version}-windows-x86_64.zip" \
  "$root/dist/paperdoll-renderer-windows-x86_64.zip"
(
  cd "$stage"
  zip -r "$root/dist/paperdoll-renderer-${version}-windows-x86_64.zip" \
    paperdoll-renderer.exe LICENSE.txt README.txt
)
cp -f "$root/dist/paperdoll-renderer-${version}-windows-x86_64.zip" \
  "$root/dist/paperdoll-renderer-windows-x86_64.zip"
echo "wrote dist/paperdoll-renderer-windows-x86_64.zip"
