#!/usr/bin/env bash
# PS2 Web Recomp local compilation helper. No files are uploaded.
# Engine: https://github.com/snuri00/ps2-web-recomp (MIT, Samir Nuri)
set -euo pipefail

readonly upstream='https://github.com/snuri00/ps2-web-recomp.git'
readonly revision='f3a550b797de04b6380394e52532c03902bb03c4'
usage() { printf 'Usage: bash compile-game.sh <build-name> </absolute/path/to/game.iso>\n'; }
if [[ "${1:-}" == '--help' || "${1:-}" == '-h' ]]; then usage; exit 0; fi
if (( $# != 2 )); then usage >&2; exit 1; fi
if (( BASH_VERSINFO[0] < 4 )); then printf 'Use Bash 4 or newer (on macOS: brew install bash).\n' >&2; exit 1; fi
export PATH="$(dirname "$BASH"):$PATH"
game="$1"
if [[ ! "$game" =~ ^[a-z0-9][a-z0-9_-]{0,39}$ ]]; then printf 'Invalid build name. Use 1-40 lowercase letters, digits, underscores or hyphens.\n' >&2; exit 1; fi
for tool in git cmake ninja python3; do
  if ! command -v "$tool" >/dev/null 2>&1; then printf 'Missing dependency: %s. Install the prerequisites shown on ps2webrecomp.com.\n' "$tool" >&2; exit 1; fi
done
if ! command -v clang++ >/dev/null 2>&1 && ! command -v g++ >/dev/null 2>&1; then printf 'Install a C++20 compiler (Clang recommended).\n' >&2; exit 1; fi
disc=$(python3 -c 'import os,sys; print(os.path.abspath(sys.argv[1]))' "$2")
if [[ ! -f "$disc" ]]; then printf 'Disc not found: %s\n' "$disc" >&2; exit 1; fi
case "$disc" in *.iso|*.ISO) ;; *) printf 'Choose an uncompressed .iso disc image.\n' >&2; exit 1 ;; esac
workspace="${PS2_RECOMP_WORKDIR:-$HOME/.local/share/ps2-web-recomp}"
repo="$workspace/upstream"
mkdir -p "$workspace"
if [[ ! -e "$repo" ]]; then
  git clone --no-checkout "$upstream" "$repo"
  git -C "$repo" checkout --detach "$revision"
else
  if [[ ! -d "$repo/.git" ]] || [[ "$(git -C "$repo" remote get-url origin)" != "$upstream" ]]; then
    printf 'The workspace contains another project. Set PS2_RECOMP_WORKDIR to an empty directory.\n' >&2; exit 1
  fi
  if [[ "$(git -C "$repo" rev-parse HEAD)" != "$revision" ]] || [[ -n "$(git -C "$repo" status --porcelain --untracked-files=no)" ]]; then
    printf 'Existing upstream checkout differs from the pinned version. It has been left unchanged. Set PS2_RECOMP_WORKDIR to a new directory.\n' >&2; exit 1
  fi
fi
if [[ -e "$repo/games/$game" || -e "$repo/build/web-$game" ]]; then
  printf 'A build named %s already exists. Choose a new build name to preserve it.\n' "$game" >&2; exit 1
fi
printf '\nCompiling locally with upstream revision %s. First run downloads Emscripten and native dependencies.\n' "$revision"
cd "$repo"
bash scripts/port.sh "$game" "$disc"
printf '\nBuild complete. In ps2webrecomp.com select these files together:\n'
printf '  %s/build/web-%s/ps2web.{html,js,wasm,data}\n' "$repo" "$game"
printf 'Include any additional generated worker JavaScript files, then select the same ISO.\n'
printf 'Keep this build and disc private. Compilation does not guarantee game compatibility.\n'
