#!/usr/bin/env bash
# Build a drop-in release zip for one game. Handles both fix methods.
#   ./tools/build_release.sh GundamBreaker4     (METHOD=suwsf)
#   ./tools/build_release.sh BurglinGnomes      (METHOD=bepinex)
# Output: dist/<Game>_UltraWide_Fix.zip
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$HERE"

GAME="${1:?usage: build_release.sh <GameName>}"
GDIR="games/$GAME"
[ -d "$GDIR" ] || { echo "[!] no such game: $GDIR"; exit 1; }
[ -f "$GDIR/game.conf" ] || { echo "[!] missing $GDIR/game.conf"; exit 1; }
# shellcheck disable=SC1090
. "$GDIR/game.conf"
METHOD="${METHOD:-suwsf}"

OUT="dist/${GAME}_UltraWide_Fix"
rm -rf "$OUT" "$OUT.zip"
mkdir -p "$OUT"

if [ "$METHOD" = "external" ]; then
  SRC="vendor/$VENDOR_PAYLOAD"
  [ -d "$SRC" ] || { echo "[!] missing vendored payload: $SRC"; exit 1; }
  cp "$SRC"/* "$OUT/" 2>/dev/null || true
  [ -n "${EXTERNAL_CONFIG:-}" ] && [ -f "$GDIR/$EXTERNAL_CONFIG" ] && cp "$GDIR/$EXTERNAL_CONFIG" "$OUT/"
  # ship the upstream license alongside, as MIT requires
  UPLIC="vendor/$(dirname "$VENDOR_PAYLOAD" | cut -d/ -f1)/LICENSE"
  [ -f "$UPLIC" ] || UPLIC="vendor/${VENDOR_PAYLOAD%%/*}/LICENSE"
  [ -f "$UPLIC" ] && cp "$UPLIC" "$OUT/UPSTREAM-LICENSE.txt"
  echo "[+] Packaged vendored external fix + our config"
elif [ "$METHOD" = "bepinex" ]; then
  BEPZIP=$(ls vendor/BepInEx_win_x64_*.zip 2>/dev/null | head -1)
  [ -f "$BEPZIP" ] || { echo "[!] missing BepInEx zip in vendor/"; exit 1; }
  [ -f "$GDIR/$PLUGIN_DLL" ] || { echo "[!] missing prebuilt plugin $GDIR/$PLUGIN_DLL"; exit 1; }
  command -v unzip >/dev/null || { echo "[!] unzip required"; exit 1; }
  unzip -o -q "$BEPZIP" -d "$OUT"
  mkdir -p "$OUT/BepInEx/plugins"
  cp "$GDIR/$PLUGIN_DLL" "$OUT/BepInEx/plugins/"
  echo "[+] Packaged BepInEx + $PLUGIN_DLL"
else
  V="vendor/SUWSF-x64"
  for f in "$V/SUWSF.asi" "$V/dsound.dll" "$V/LICENSE" "$GDIR/SUWSF.ini"; do
    [ -f "$f" ] || { echo "[!] missing $f"; exit 1; }
  done
  cp "$V/SUWSF.asi" "$V/dsound.dll" "$GDIR/SUWSF.ini" "$OUT/"
  cp "$V/LICENSE" "$OUT/SUWSF-LICENSE.txt"
  echo "[+] Packaged SUWSF + patch ini"
fi

cp "$GDIR/README.md" "$OUT/README.md" 2>/dev/null || true
cp THIRD_PARTY.md LICENSE "$OUT/" 2>/dev/null || true

( cd dist && zip -r -q "${GAME}_UltraWide_Fix.zip" "${GAME}_UltraWide_Fix" )
echo "[+] Built dist/${GAME}_UltraWide_Fix.zip"
( cd dist && sha256sum "${GAME}_UltraWide_Fix.zip" )
