#!/usr/bin/env bash
# Builds PlayAgain's PSP core: public/cores/ppsspp/ppsspp.{js,wasm}.
#
# Reproducible: the same PPSSPP commit and Emscripten give the same bytes.
# PPSSPP comes from `git archive` of the pinned commit, and each submodule the
# libretro core compiles from `git archive` of the commit that one pins (a
# plain tree, no .git). ppsspp-3039c4e.patch is applied (what it changes and
# why is at its top), then ppsspp-3039c4e-webgl.patch (PPSSPP's GL renderer run
# on the one thread) and ppsspp-3039c4e-wasmjit.patch (the IR interpreter's two
# ops for PlayAgain's WebAssembly JIT, and FMul's NaN rule, which the JIT shares),
# then PPSSPP's own libretro Makefile
# (platform=emscripten) builds the core as a static library: the IR interpreter,
# the GL renderer (on WebGL2, chosen at run time: pa_set_renderer) and the
# software renderer, FFmpeg from ext/ffmpeg for movies and ATRAC3+, none of
# PPSSPP's native JITs, no threads. zlib comes from PPSSPP's ext/zlib (no
# Emscripten ports). PlayAgain's shim (pa_ppsspp.cpp) and its WebAssembly JIT
# for the IR (pa_wasmjit.cpp, WasmEmitter.h, pa_wasmjit.js; off unless
# pa_set_jit(1)) are linked against it. The script refuses other Emscripten
# versions and writes SHA256SUMS beside itself; record the wasm's SHA-256 in
# ../README.md. Run it twice and compare.
#
#   bash public/cores/ppsspp/source/build.sh
#
# Needs: git, make, patch and a C++ compiler for Emscripten's tools. Emscripten
# is installed into EMSDK_DIR on first run. Takes about 5 minutes on 4 cores.
set -euo pipefail

PPSSPP_COMMIT="3039c4ea96e3430cf4dcad9d34f00e298ac9ace1" # master, 2026-11-05 (v1.20.4-4487)
PPSSPP_VERSION="v1.20.4-4487-g3039c4ea9"                 # what `git describe` says there
EMSCRIPTEN_VERSION="6.0.12"
# The submodules the libretro core compiles or includes; each is archived at the commit the
# superproject pins. ext/armips has one of its own (ext/filesystem).
SUBMODULES=(
  libretro/libretro-common ext/armips ext/glslang ext/SPIRV-Cross ext/miniupnp ext/zstd
  ext/cpu_features ext/rcheevos ext/libchdr ext/lua ext/aemu_postoffice ext/libadrenotools
  ext/OpenXR-SDK ext/rapidjson
)

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUT="$(cd "$HERE/.." && pwd)"
EMSDK_DIR="${EMSDK_DIR:-$HOME/.cache/playagain/emsdk}"
WORK="${WORK:-$HOME/.cache/playagain/ppsspp}"
JOBS="${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu)}"
PATCH="$HERE/ppsspp-${PPSSPP_COMMIT:0:7}.patch"
WEBGL_PATCH="$HERE/ppsspp-${PPSSPP_COMMIT:0:7}-webgl.patch"
WASMJIT_PATCH="$HERE/ppsspp-${PPSSPP_COMMIT:0:7}-wasmjit.patch"

# --- 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; }

# --- PPSSPP and its submodules at the pinned commits, as a plain tree ---------
mkdir -p "$WORK"
if [ ! -d "$WORK/git/.git" ]; then
  git clone --quiet --filter=blob:none https://github.com/hrydgard/ppsspp.git "$WORK/git"
fi
git -C "$WORK/git" cat-file -e "$PPSSPP_COMMIT^{commit}" 2>/dev/null || git -C "$WORK/git" fetch --quiet origin
git -C "$WORK/git" -c advice.detachedHead=false checkout --quiet --force "$PPSSPP_COMMIT"
git -C "$WORK/git" submodule update --init --quiet -- "${SUBMODULES[@]}"
git -C "$WORK/git/ext/armips" submodule update --init --quiet -- ext/filesystem

SRC="$WORK/src"
rm -rf "$SRC"
mkdir -p "$SRC"
git -C "$WORK/git" archive --format=tar "$PPSSPP_COMMIT" | tar -x -C "$SRC"
archive_submodule() { # <superproject> <commit there> <path>
  local pinned
  pinned="$(git -C "$1" ls-tree "$2" "$3" | awk '{print $3}')"
  mkdir -p "$SRC/$4"
  git -C "$1/$3" archive --format=tar "$pinned" | tar -x -C "$SRC/$4"
}
for path in "${SUBMODULES[@]}"; do
  archive_submodule "$WORK/git" "$PPSSPP_COMMIT" "$path" "$path"
done
archive_submodule "$WORK/git/ext/armips" HEAD ext/filesystem ext/armips/ext/filesystem

patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch < "$PATCH"
patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch < "$WEBGL_PATCH"
patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch < "$WASMJIT_PATCH"
printf 'const char *PPSSPP_GIT_VERSION = "%s";\n#define PPSSPP_GIT_VERSION_NO_UPDATE 1\n' "$PPSSPP_VERSION" > "$SRC/git-version.cpp"

# --- the libretro core as a static library ------------------------------------
# -flto here and at the link: the IR interpreter (about 70% of a 3D race's time, profiled) gets the
# memory and VFPU helpers it calls inlined across files; measured in WebKit on a race, 15 ms a frame
# became 10-12 ms (Safari's 55-57 fps became 60).
# platform=emscripten, with its flags but no threads, plus FFmpeg (ext/ffmpeg, plain C) and the
# file-prefix maps; CPUFLAGS drops the x86 dynarec's -m32 -msse (its emitters are compiled but
# never run: no JIT). The archive is named .a so em++ links it as one.
export SOURCE_DATE_EPOCH="$(git -C "$WORK/git" log -1 --format=%ct "$PPSSPP_COMMIT")"
MAP="-ffile-prefix-map=$SRC=ppsspp -ffile-prefix-map=$HERE=pa"
emmake make -C "$SRC/libretro" -j"$JOBS" --no-print-directory platform=emscripten \
  GIT_VERSION="$PPSSPP_VERSION" TARGET=libppsspp_libretro.a WITH_DYNAREC=1 CPUFLAGS="-D_ARCH_32" BUILD_FFMPEG=1 \
  PLATCFLAGS="-flto -msimd128 -msse3 -mssse3 -msse4.1 -D__EMSCRIPTEN__ -DNO_MMAP -DUSE_FFMPEG -Wno-everything $MAP" \
  >/dev/null

# --- zlib, from PPSSPP's tree (a frontend supplies it when STATIC_LINKING) -----
ZOBJ=()
mkdir -p "$WORK/zlib"
for c in adler32 compress crc32 deflate gzclose gzlib gzread gzwrite inffast inflate inftrees trees uncompr zutil; do
  emcc -O3 -DNDEBUG -Wno-everything $MAP -c "$SRC/ext/zlib/$c.c" -o "$WORK/zlib/$c.o"
  ZOBJ+=("$WORK/zlib/$c.o")
done

# --- the shim, linked against both ---------------------------------------------
EXPORTS="_malloc,_free"
for f in set_renderer renderer presented init set_verbose set_clock load load_bytes error set_keys set_axes run_frame fb fb_width fb_height \
         audio_available read_audio audio_rate frame_rate state_size save_state load_state ram_ptr ram_size digest \
         saves_size saves_export saves_import saves_dirty frame_count \
         set_jit jit_active jit_service jit_config jit_stats jit_stats_reset jit_selftest jit_selftest_report; do
  EXPORTS="$EXPORTS,_pa_$f"
done

# --wrap: the host's clock and time zone stay out of the guest (pa_ppsspp.cpp).
# --embed-file: PPSSPP's own assets the core reads from <system>/PPSSPP (the system dialogs'
# font atlas, its picture and its glyph table, and the per-game compatibility list); no Sony files.
# -sFULL_ES3 and -lGL: the GL renderer's GLES 3 calls on WebGL2 (PPSSPP's gl3stub wants
# glMapBufferRange and the like, which Emscripten defines only with it); OFFSCREENCANVAS_SUPPORT:
# its context on the worker's OffscreenCanvas (Module.canvas).
# -sALLOW_TABLE_GROWTH and --js-library pa_wasmjit.js: the JIT grows the function table in 64k
# chunks and puts the functions of the modules it compiles in its slots (pa_wasmjit.js).
# shellcheck disable=SC2086
em++ "$HERE/pa_ppsspp.cpp" "$HERE/pa_wasmjit.cpp" "${ZOBJ[@]}" "$SRC/libretro/libppsspp_libretro.a" \
  -I"$SRC" -I"$SRC/Common" -I"$SRC/libretro" -I"$SRC/ext" -I"$SRC/libretro/libretro-common/include" \
  -std=c++17 -O3 -DNDEBUG -D__LIBRETRO__ -DPPSSPP -DGLES -DUSING_GLES2 -DNO_MMAP -DUSE_FFMPEG \
  -msimd128 -msse3 -mssse3 -msse4.1 -Wno-everything $MAP -flto \
  -sMODULARIZE=1 -sEXPORT_NAME=createPpssppModule -sENVIRONMENT=web,worker \
  -sFILESYSTEM=1 -lworkerfs.js -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=268435456 -sMAXIMUM_MEMORY=4294967296 \
  -sALLOW_TABLE_GROWTH=1 --js-library "$HERE/pa_wasmjit.js" \
  -sSTACK_SIZE=4194304 -sMAX_WEBGL_VERSION=2 -sMIN_WEBGL_VERSION=2 -sFULL_ES3=1 -sOFFSCREENCANVAS_SUPPORT=1 -lGL \
  -sEXPORTED_FUNCTIONS="$EXPORTS" -sEXPORTED_RUNTIME_METHODS=HEAPU8,HEAP16,HEAPU32,FS \
  -Wl,--wrap=time,--wrap=localtime,--wrap=localtime_r,--wrap=mktime \
  --embed-file "$SRC/assets/ppge_atlas.zim@/pa/system/PPSSPP/ppge_atlas.zim" \
  --embed-file "$SRC/assets/ppge_atlas.meta@/pa/system/PPSSPP/ppge_atlas.meta" \
  --embed-file "$SRC/assets/compat.ini@/pa/system/PPSSPP/compat.ini" \
  -o "$OUT/ppsspp.js" 2> >(grep -v "main. is defined in the input files" >&2)

# --- licences: PPSSPP's (GPL-2.0-or-later, with the PSPSDK's BSD notice), the GPL-3.0 the
# combination is under (libkirk, xBRZ and aemu_postoffice are GPL-3.0), FFmpeg's LGPL-2.1, and
# the notices of everything else linked in, as the tree carries them.
cp "$SRC/LICENSE.TXT" "$OUT/LICENSE.ppsspp.txt"
cp "$SRC/ext/aemu_postoffice/gpl-3.0.txt" "$OUT/LICENSE.gpl-3.0.txt"
cp "$SRC/ext/ffmpeg/COPYING.LGPLv2.1" "$OUT/LICENSE.ffmpeg-lgpl.txt"
{
  echo "Third-party notices for ppsspp.wasm, from the PPSSPP $PPSSPP_COMMIT source tree."
  for f in ext/zlib/LICENSE ext/zstd/LICENSE ext/glslang/LICENSE.txt ext/SPIRV-Cross/LICENSE ext/libchdr/LICENSE.txt \
           ext/rcheevos/LICENSE ext/armips/LICENSE.txt ext/armips/ext/filesystem/LICENSE ext/miniupnp/LICENSE \
           ext/cpu_features/LICENSE ext/cityhash/COPYING ext/snappy/COPYING ext/udis86/LICENSE ext/rapidjson/license.txt \
           ext/gason/LICENSE ext/libdeflate/COPYING ext/aemu_postoffice/LICENSE ext/libadrenotools/LICENSE \
           ext/ffmpeg/LICENSE.md; do
    printf '\n===== %s =====\n\n' "$f"
    cat "$SRC/$f"
  done
  # Components whose notice is in a source file's header rather than a file of its own.
  for f in ext/lua/lua.h ext/xxhash.h ext/libzip/zip.h ext/libpng17/png.h ext/sfmt19937/SFMT.h ext/libkirk/kirk_engine.c \
           ext/xbrz/xbrz.h ext/jpge/jpgd.h ext/imgui/imgui.h ext/glew/GL/glew.h ext/basis_universal/basisu_transcoder.h \
           libretro/libretro-common/include/libretro.h; do
    [ -f "$SRC/$f" ] || continue
    printf '\n===== %s (header) =====\n\n' "$f"
    awk 'NR <= 60 { print } /\*\// { exit }' "$SRC/$f"
  done
  printf '\n===== ext/lua/lua.h (MIT notice) =====\n\n'
  sed -n '/^\* Copyright (C) 1994/,/\*\//p' "$SRC/ext/lua/lua.h"
} > "$OUT/LICENSE.notices.txt"
(cd "$HERE" && shasum -a 256 build.sh pa_ppsspp.cpp pa_wasmjit.cpp pa_wasmjit.h pa_wasmjit.js WasmEmitter.h \
  "$(basename "$PATCH")" "$(basename "$WEBGL_PATCH")" "$(basename "$WASMJIT_PATCH")" ../ppsspp.js ../ppsspp.wasm > SHA256SUMS)
ls -l "$OUT/ppsspp.js" "$OUT/ppsspp.wasm"
shasum -a 256 "$OUT/ppsspp.wasm"
