#!/usr/bin/env bash
# Builds PCSX-ReARMed (libretro) to WebAssembly — PlayAgain's PlayStation
# core (public/cores/pcsx-rearmed/). It replaced eNGE-JS, which was 3–5×
# faster on test programs and played one commercial disc in four; see
# docs/adr/ADR-psx-core.md for the measurements and the revision.
#
# In wasm the core is the interpreter (both dynarecs emit native code) with
# the NEON GPU on SIMD128 — 3.6–4.7× realtime on OpenBIOS + pcsx-redux test
# programs (Node 22, Apple Silicon, 2026-08-25).
#
# Requires: git, make and Python 3.10+. Emscripten is installed into EMSDK_DIR
# on first run.
# Output: pcsx_rearmed.{js,wasm} and pcsx_rearmed.nosimd.{js,wasm} beside
# this folder (public/cores/pcsx-rearmed/), committed:
#   bash public/cores/pcsx-rearmed/source/build.sh
#
# The commit below is the one the core names itself ("r26 da2cb8e", libretro's
# GIT_VERSION), plus PlayAgain's patches in patches/ (NO_PATCHES=1 leaves them
# out). The first:
#   0001-netplay-save-subcycle-and-pad-poll.patch — the state keeps what a load
#   used to lose (the interpreter's subCycle, the pad exchange position, the
#   cards' "new card" flag), so that any load is exact. The state's size and
#   every offset in it stay; an older state still loads.
# This script is published with the core (linked from /licenses): with that
# commit and those patches it is the source of the shipped binary.
#
# Toolchain: Emscripten 6.0.12 (clang llvm-project 55ea1f4e), the one the
# SameBoy and mGBA builds pin; the script refuses another. The shipped files
# before the patch came from an Emscripten 6.0 release whose clang was
# llvm-project 4bfd08c2.
#
# Network: the upstream source at the commit below (once; it stays in WORK),
# nothing else. Inflate is upstream's own bundled miniz, not Emscripten's zlib
# port, which is another download at build time.
set -euo pipefail

UPSTREAM_COMMIT="da2cb8ecd17fd0932ab6d94774c0522beebce6e3"
EMSCRIPTEN_VERSION="6.0.12"
LLVM_COMMIT="55ea1f4ebea23d0355d5cdb075f1e12f28ab82d0"
OUT="$(cd "$(dirname "$0")/.." && pwd)"
EMSDK_DIR="${EMSDK_DIR:-$HOME/.cache/playagain/emsdk}"
WORK="${WORK:-$HOME/.cache/playagain/pcsx-rearmed}"

# --- toolchain ---------------------------------------------------------------
if [ ! -x "$EMSDK_DIR/emsdk" ]; then
  git clone https://github.com/emscripten-core/emsdk.git "$EMSDK_DIR"
fi
"$EMSDK_DIR/emsdk" install "$EMSCRIPTEN_VERSION" >/dev/null
"$EMSDK_DIR/emsdk" activate "$EMSCRIPTEN_VERSION" >/dev/null
# shellcheck disable=SC1091
source "$EMSDK_DIR/emsdk_env.sh" >/dev/null 2>&1
emcc --version | head -1 | grep -q " $EMSCRIPTEN_VERSION " || { echo "need Emscripten $EMSCRIPTEN_VERSION" >&2; exit 1; }
"$EMSDK_DIR/upstream/bin/clang" --version | head -1 | grep -q "$LLVM_COMMIT" || { echo "need clang from llvm-project $LLVM_COMMIT" >&2; exit 1; }

# --- source ------------------------------------------------------------------
if ! git -C "$WORK/src" cat-file -e "$UPSTREAM_COMMIT^{commit}" 2>/dev/null; then
  rm -rf "$WORK/src"
  git init -q "$WORK/src"
  git -C "$WORK/src" fetch -q --depth 1 https://github.com/libretro/pcsx_rearmed.git "$UPSTREAM_COMMIT"
fi
cd "$WORK/src"
git checkout -qf "$UPSTREAM_COMMIT"
git clean -fdxq
if [ "${NO_PATCHES:-0}" != "1" ]; then
  git apply "$OUT/source/patches/"*.patch
fi
# frontend/main.c prints __DATE__: the commit's date, so that two builds are one.
SOURCE_DATE_EPOCH="$(git show -s --format=%ct "$UPSTREAM_COMMIT")"
export SOURCE_DATE_EPOCH
# Upstream's bundled miniz for inflate on every build: see the header.
use_miniz() {
  python3 - <<'PYEOF'
s = open("Makefile.libretro").read()
s = s.replace("   USE_MINIZ = 0\n   CFLAGS += -sUSE_ZLIB=1\n   EXTRA_LDFLAGS += -sUSE_ZLIB=1\n", "   USE_MINIZ = 1\n")
assert "+= -sUSE_ZLIB" not in s and "USE_MINIZ = 1" in s
open("Makefile.libretro", "w").write(s)
PYEOF
}
use_miniz

# The Makefile has an emscripten platform of its own: interpreter (the
# dynarecs need native code), NEON GPU via SIMD128, libchdr for .chd, no
# threads.
emmake make -f Makefile.libretro platform=emscripten -j"$(sysctl -n hw.ncpu 2>/dev/null || nproc)"
cp pcsx_rearmed_libretro_emscripten.bc librearmed.a   # it IS an ar archive

mkdir -p "$OUT"
emcc librearmed.a \
  -o "$OUT/pcsx_rearmed.js" \
  -O3 -msimd128 -sENVIRONMENT=web,worker -sMODULARIZE=1 -sEXPORT_NAME=createPcsxRearmedModule \
  --profiling-funcs -lworkerfs.js \
  -sALLOW_MEMORY_GROWTH=1 -sALLOW_TABLE_GROWTH=1 -sINITIAL_MEMORY=64MB -sFILESYSTEM=1 \
  -sEXPORTED_FUNCTIONS='["_malloc","_free","_retro_init","_retro_deinit","_retro_api_version","_retro_get_system_info","_retro_get_system_av_info","_retro_set_environment","_retro_set_video_refresh","_retro_set_audio_sample","_retro_set_audio_sample_batch","_retro_set_input_poll","_retro_set_input_state","_retro_set_controller_port_device","_retro_reset","_retro_run","_retro_serialize_size","_retro_serialize","_retro_unserialize","_retro_load_game","_retro_unload_game","_retro_get_region","_retro_get_memory_data","_retro_get_memory_size"]' \
  -sEXPORTED_RUNTIME_METHODS='["addFunction","removeFunction","getValue","setValue","FS","HEAPU8","HEAP16","HEAP32","HEAPF32","UTF8ToString","stringToUTF8","lengthBytesUTF8","WORKERFS","MEMFS"]'

# Second build: no wasm SIMD, gpu_unai instead of the NEON GPU — for
# browsers (older TVs, mostly) whose WebAssembly lacks SIMD128. The worker
# probes at start and imports whichever build the browser can run.
git checkout Makefile.libretro
use_miniz
python3 - <<'PYEOF2'
s = open("Makefile.libretro").read()
s = s.replace("   CFLAGS += -msimd128 -ftree-vectorize", "   CFLAGS += -ftree-vectorize")
s = s.replace("   BUILTIN_GPU = neon", "   BUILTIN_GPU = unai")
s = s.replace("   plugins/gpu_neon/psx_gpu/psx_gpu_simd.o: CFLAGS += -msse4.2\n", "")
open("Makefile.libretro", "w").write(s)
PYEOF2
emmake make -f Makefile.libretro platform=emscripten clean
emmake make -f Makefile.libretro platform=emscripten -j"$(sysctl -n hw.ncpu 2>/dev/null || nproc)"
cp pcsx_rearmed_libretro_emscripten.bc librearmed-nosimd.a
emcc librearmed-nosimd.a \
  -o "$OUT/pcsx_rearmed.nosimd.js" \
  -O3 -sENVIRONMENT=web,worker -sMODULARIZE=1 -sEXPORT_NAME=createPcsxRearmedModule \
  --profiling-funcs -lworkerfs.js \
  -sALLOW_MEMORY_GROWTH=1 -sALLOW_TABLE_GROWTH=1 -sINITIAL_MEMORY=64MB -sFILESYSTEM=1 \
  -sEXPORTED_FUNCTIONS='["_malloc","_free","_retro_init","_retro_deinit","_retro_api_version","_retro_get_system_info","_retro_get_system_av_info","_retro_set_environment","_retro_set_video_refresh","_retro_set_audio_sample","_retro_set_audio_sample_batch","_retro_set_input_poll","_retro_set_input_state","_retro_set_controller_port_device","_retro_reset","_retro_run","_retro_serialize_size","_retro_serialize","_retro_unserialize","_retro_load_game","_retro_unload_game","_retro_get_region","_retro_get_memory_data","_retro_get_memory_size"]' \
  -sEXPORTED_RUNTIME_METHODS='["addFunction","removeFunction","getValue","setValue","FS","HEAPU8","HEAP16","HEAP32","HEAPF32","UTF8ToString","stringToUTF8","lengthBytesUTF8","WORKERFS","MEMFS"]' 

cp COPYING "$OUT/LICENSE.pcsx-rearmed.txt"
echo "built -> $OUT (GPL-2.0 — not a PlayAgain core; see the header)"
