#!/usr/bin/env bash
# Builds PlayAgain's PlayStation 2 core: TabStationToo's pcsx2-wasm target (PCSX2
# compiled to WebAssembly, with its own wasm JITs and a WebGPU renderer) at one
# pinned commit, with Emscripten 6.0.12, plus PlayAgain's shim (pause, reset,
# four players), into public/cores/pcsx2/.
#
#   bash public/cores/pcsx2/source/build.sh            # deps (once) + core
#   SMOKE=1 bash public/cores/pcsx2/source/build.sh    # + TabStationToo's headless smoke test
#
# It writes pcsx2-wasm.{js,wasm,data}, upstream's web/disc-worker.js (verbatim,
# GPL-3), LICENSE.gpl3.txt and LICENSE.notices.txt into OUT (default: the folder
# above this script) and, when OUT is that folder, SHA256SUMS beside itself;
# record the wasm's SHA-256 in ../README.md (a test checks both). The build log,
# the blockers met and how each was passed are in docs/cores/pcsx2/README.md.
#
# Steps, as TabStationToo's pcsx2-wasm/README.md "Build" and its CI
# (.github/workflows/pages.yml) give them:
#   1. tools/wasm/build-dependencies-wasm.sh deps-wasm  (zlib, libpng+apng, libjpeg-turbo,
#      LZ4, Zstandard, WebP, SDL3, FreeType, PlutoVG, PlutoSVG, RapidYAML; static, -pthread)
#   2. emcmake cmake -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Release
#        -DCMAKE_PREFIX_PATH=deps-wasm -DCMAKE_FIND_ROOT_PATH=deps-wasm
#        -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DENABLE_GSRUNNER=OFF -DENABLE_TESTS=OFF
#   3. ninja -C build-wasm pcsx2-wasm
# Five patches beside this script change upstream, in this order (each explains
# itself at its top):
#   tabstationtoo-5a9a7b4-deps-git.patch  the dependency script: four sources from git
#                                         tags instead of tarballs, no build paths in
#                                         the libraries
#   tabstationtoo-5a9a7b4-pa-shim.patch   pcsx2-wasm: pa_ps2_pause, pa_ps2_reset,
#                                         pa_ps2_set_ports, pa_ps2_set_turbo, five pad ports, eight
#                                         vibration words
#   tabstationtoo-5a9a7b4-pa-hw-ad-blend.patch  the hardware renderer on WebGPU: blending by
#                                         destination alpha without a feedback copy
#   tabstationtoo-5a9a7b4-pa-vu1-cache.patch    the VU1 JIT: room in its program cache, a drop
#                                         that does not search
#   tabstationtoo-5a9a7b4-pa-colclip-unfilterable.patch  the WebGPU device: a colour clip
#                                         target read through the unfilterable layout
#
# Reproducible: two builds on one machine give the same three files (../README.md
# has their SHA-256). A Linux machine and a Mac agree on the .js and .data but not
# yet on the .wasm, so the shipped wasm is the one ../README.md names, built on the
# machine it names.
#
# No BIOS, disc, firmware or key is fetched or needed to build; the smoke test
# boots the page to its "no BIOS" intake and checks nothing else.
#
# Needs: git, curl, shasum, tar, xz, gzip, patch, ninja, python3 (with venv
# and pip: CMake 4.4.4 comes from PyPI into WORK); node 22+ and Chrome for
# SMOKE=1 (CHROME=/path/to/chrome). Emscripten is installed into EMSDK_DIR on
# first run. From nothing (fetches and libraries included): about 3.5 minutes on
# a Mac mini M4, 5 on 4 Linux cores.
#
# WORK (default ~/.cache/playagain/pcsx2-build, about 1 GB) holds the checkout,
# CMake's venv, the libraries and the build. The script forces its checkout to
# the pinned commit, cleans it and patches it, so WORK must never be
# ~/.cache/playagain/pcsx2: that folder's src/ is the unpatched reference tree
# the design and pa_ps2_exports.md cite by line, and the script refuses it.
set -euo pipefail
export LC_ALL=C

TST_COMMIT="5a9a7b489e428f3cea87d52621429f749c969f41" # TabStationToo, branch wasm, 2026-10-30
EMSCRIPTEN_VERSION="6.0.12"
CMAKE_VERSION="4.4.4" # TabStationToo's CI: CMake 3.x configures libzip without a usable off_t under Emscripten

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EMSDK_DIR="${EMSDK_DIR:-$HOME/.cache/playagain/emsdk}"
WORK="${WORK:-$HOME/.cache/playagain/pcsx2-build}"
OUT="${OUT:-$(cd "$HERE/.." && pwd)}"
JOBS="${JOBS:-$(getconf _NPROCESSORS_ONLN)}"
SMOKE="${SMOKE:-0}"
PATCHES=("tabstationtoo-${TST_COMMIT:0:7}-deps-git.patch" "tabstationtoo-${TST_COMMIT:0:7}-pa-shim.patch"
  "tabstationtoo-${TST_COMMIT:0:7}-pa-hw-ad-blend.patch" "tabstationtoo-${TST_COMMIT:0:7}-pa-vu1-cache.patch"
  "tabstationtoo-${TST_COMMIT:0:7}-pa-colclip-unfilterable.patch")
REFERENCE="$HOME/.cache/playagain/pcsx2" # the unpatched reference checkout (above); never a WORK
mkdir -p "$WORK"
if [ -d "$REFERENCE" ] && [ "$WORK" -ef "$REFERENCE" ]; then
  echo "WORK=$WORK is the reference checkout's folder, which this script would patch; use another WORK" >&2
  exit 1
fi

# --- 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; }
EM_ROOT="$(cd "$(dirname "$(command -v emcc)")" && pwd)"
# CMake from PyPI, as TabStationToo's CI installs it, in a venv of its own;
# only cmake/ctest/cpack go on PATH.
CMAKE_VENV="$WORK/cmake-$CMAKE_VERSION"
if ! "$CMAKE_VENV/bin/cmake" --version 2>/dev/null | grep -q "version $CMAKE_VERSION\$"; then
  rm -rf "$CMAKE_VENV"
  python3 -m venv "$CMAKE_VENV"
  "$CMAKE_VENV/bin/pip" install --quiet --disable-pip-version-check "cmake==$CMAKE_VERSION"
fi
mkdir -p "$WORK/bin"
for t in cmake ctest cpack; do ln -sf "$CMAKE_VENV/bin/$t" "$WORK/bin/$t"; done
export PATH="$WORK/bin:$PATH"
cmake --version | head -1 | grep -q "version $CMAKE_VERSION\$" || { echo "need CMake $CMAKE_VERSION" >&2; exit 1; }

# --- TabStationToo at the pinned commit, patched ------------------------------
# One commit, fetched shallow: the repository carries PCSX2's whole history
# (23k commits). The tree stays a git checkout because PCSX2's CMake names the
# build after it (git rev-parse --short HEAD, commit date); a shallow clone
# without tags gives the same name every time.
SRC="$WORK/src"
if [ ! -d "$SRC/.git" ]; then
  git init --quiet "$SRC"
  git -C "$SRC" remote add origin https://github.com/TabStationToo/TabStationToo.git
fi
git -C "$SRC" cat-file -e "$TST_COMMIT^{commit}" 2>/dev/null || git -C "$SRC" fetch --quiet --depth 1 origin "$TST_COMMIT"
git -C "$SRC" checkout --quiet --force "$TST_COMMIT"
git -C "$SRC" clean --quiet -fdx
for p in "${PATCHES[@]}"; do
  git -C "$SRC" apply "$HERE/$p"
done

# --- third-party libraries (once; rebuilt when the patched script changes) ----
# The script downloads into ./deps-build-wasm and installs into its argument.
DEPS="$WORK/deps-wasm"
DEPS_BUILD="$WORK/deps-build-wasm"
DEPS_KEY="$(shasum -a 256 "$SRC/tools/wasm/build-dependencies-wasm.sh" | cut -d' ' -f1) emscripten-$EMSCRIPTEN_VERSION cmake-$CMAKE_VERSION"
if [ "$(cat "$DEPS/.pa-key" 2>/dev/null)" != "$DEPS_KEY" ]; then
  rm -rf "$DEPS"
  (cd "$WORK" && bash "$SRC/tools/wasm/build-dependencies-wasm.sh" "$DEPS")
  echo "$DEPS_KEY" > "$DEPS/.pa-key"
fi

# --- pcsx2-wasm ----------------------------------------------------------------
# The README's flags plus the two its CI adds (.github/workflows/pages.yml):
# without CMAKE_FIND_ROOT_PATH, Emscripten's toolchain file re-roots
# CMAKE_PREFIX_PATH under its sysroot and finds neither zlib nor libpng.
# -ffile-prefix-map keeps this machine's paths out of the binary (assert
# messages, __FILE__ in RapidYAML's headers), so two work directories, or two
# machines, give the same bytes; the dependency patch does the same for the
# libraries.
BUILD="$WORK/build-wasm"
PREFIX_MAPS="-ffile-prefix-map=$SRC=tabstationtoo -ffile-prefix-map=$DEPS=deps-wasm -ffile-prefix-map=$BUILD=build-wasm"
emcmake cmake -S "$SRC" -B "$BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_PREFIX_PATH="$DEPS" -DCMAKE_FIND_ROOT_PATH="$DEPS" -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \
  -DENABLE_GSRUNNER=OFF -DENABLE_TESTS=OFF \
  -DCMAKE_C_FLAGS="$PREFIX_MAPS" -DCMAKE_CXX_FLAGS="$PREFIX_MAPS"
ninja -C "$BUILD" -j "$JOBS" pcsx2-wasm 2>&1 | tee "$WORK/ninja.log"
# wasm-ld turns calls with mismatched signatures into traps; TabStationToo's CI
# fails the build on them, and so does this.
if grep -n "signature mismatch" "$WORK/ninja.log"; then
  echo "the link reported signature mismatches" >&2
  exit 1
fi
# The shim's exports must be there (a patch that did not apply would build without them).
for f in _pa_ps2_pause _pa_ps2_reset _pa_ps2_set_ports _pa_ps2_set_turbo _pcsx2web_set_upscale; do
  grep -q "Module\[\"$f\"\]" "$BUILD/bin/pcsx2-wasm.js" || { echo "pcsx2-wasm.js does not export $f" >&2; exit 1; }
done

# --- outputs, licences and notices ------------------------------------------------
mkdir -p "$OUT"
for f in pcsx2-wasm.js pcsx2-wasm.wasm pcsx2-wasm.data; do
  cp "$BUILD/bin/$f" "$OUT/$f"
done
cp "$SRC/pcsx2-wasm/web/disc-worker.js" "$OUT/disc-worker.js"
cp "$SRC/COPYING.GPLv3" "$OUT/LICENSE.gpl3.txt"

# The notices of everything linked into pcsx2-wasm.wasm besides PCSX2 and TabStationToo's own
# code (GPL-3.0-or-later, LICENSE.gpl3.txt), or packed into pcsx2-wasm.data, as each source tree
# carries them. The link list is build-wasm/build.ninja's for bin/pcsx2-wasm.js.
notice() { # LABEL FILE
  [ -f "$2" ] || { echo "notice: $2 is missing (delete $DEPS to rebuild the libraries)" >&2; exit 1; }
  printf '\n===== %s =====\n\n' "$1"
  cat "$2"
}
header_notice() { # LABEL FILE: the file's first comment block
  [ -f "$2" ] || { echo "notice: $2 is missing" >&2; exit 1; }
  printf '\n===== %s (header) =====\n\n' "$1"
  awk 'NR <= 60 { print } /\*\// { exit }' "$2"
}
DAWN="$(em-config CACHE)/ports/emdawnwebgpu/emdawnwebgpu_pkg"
{
  echo "Third-party notices for pcsx2-wasm.wasm, pcsx2-wasm.js and pcsx2-wasm.data, built from"
  echo "TabStationToo $TST_COMMIT with Emscripten $EMSCRIPTEN_VERSION."
  echo
  echo "PCSX2 and TabStationToo are GPL-3.0-or-later (LICENSE.gpl3.txt), and the whole is distributed"
  echo "under it. Two parts linked in are GPL-2.0-or-later, used here under GPL-3.0: FreeSurround"
  echo "(3rdparty/freesurround) and the GNU demangler from libiberty (3rdparty/demangler, with the"
  echo "libgcc-style linking exception in its file headers). The rest keep the licences below."
  echo
  echo "Libraries built by tools/wasm/build-dependencies-wasm.sh:"
  notice "zlib 1.3.1 (LICENSE)" "$DEPS_BUILD/zlib-1.3.1/LICENSE"
  notice "libpng 1.6.58, with the APNG patch (LICENSE)" "$DEPS_BUILD/libpng-1.6.58/LICENSE"
  notice "libjpeg-turbo 3.2.0 (LICENSE.md: IJG, BSD-3-Clause, zlib)" "$DEPS_BUILD/libjpeg-turbo-3.2.0/LICENSE.md"
  notice "libjpeg-turbo 3.2.0 (README.ijg)" "$DEPS_BUILD/libjpeg-turbo-3.2.0/README.ijg"
  notice "LZ4 1.10.0 (LICENSE)" "$DEPS_BUILD/lz4-1.10.0/LICENSE"
  notice "Zstandard 1.5.7 (LICENSE)" "$DEPS_BUILD/zstd-1.5.7/LICENSE"
  notice "WebP 1.6.0, libwebp and libsharpyuv (COPYING)" "$DEPS_BUILD/libwebp-1.6.0/COPYING"
  notice "SDL 3.4.18 (LICENSE.txt)" "$DEPS_BUILD/SDL3-3.4.18/LICENSE.txt"
  notice "FreeType 2.13.3, used under the FreeType License (docs/FTL.TXT)" "$DEPS_BUILD/freetype-2.13.3/docs/FTL.TXT"
  notice "PlutoVG 1.3.3 (LICENSE)" "$DEPS_BUILD/plutovg-1.3.3/LICENSE"
  notice "PlutoSVG 0.0.8 (LICENSE)" "$DEPS_BUILD/plutosvg-0.0.8/LICENSE"
  notice "RapidYAML 0.12.1 (LICENSE.txt)" "$DEPS_BUILD/rapidyaml-0.12.1-src/LICENSE.txt"
  notice "c4core, inside RapidYAML 0.12.1 (ext/c4core/LICENSE.txt)" "$DEPS_BUILD/rapidyaml-0.12.1-src/ext/c4core/LICENSE.txt"
  notice "c4core, inside RapidYAML 0.12.1 (ext/c4core/LICENSE-BOOST.txt)" "$DEPS_BUILD/rapidyaml-0.12.1-src/ext/c4core/LICENSE-BOOST.txt"
  echo
  echo "TabStationToo's 3rdparty/ (linked libraries and headers):"
  notice "cpuinfo (3rdparty/cpuinfo/LICENSE)" "$SRC/3rdparty/cpuinfo/LICENSE"
  notice "cubeb (3rdparty/cubeb/LICENSE)" "$SRC/3rdparty/cubeb/LICENSE"
  header_notice "Speex resampler, inside cubeb (3rdparty/cubeb/subprojects/speex/resample.c)" "$SRC/3rdparty/cubeb/subprojects/speex/resample.c"
  notice "discord-rpc (3rdparty/discord-rpc/LICENSE)" "$SRC/3rdparty/discord-rpc/LICENSE"
  notice "{fmt} (3rdparty/fmt/LICENSE)" "$SRC/3rdparty/fmt/LICENSE"
  notice "Dear ImGui (3rdparty/imgui/LICENSE.txt)" "$SRC/3rdparty/imgui/LICENSE.txt"
  notice "libchdr (3rdparty/libchdr/LICENSE.txt)" "$SRC/3rdparty/libchdr/LICENSE.txt"
  notice "libzip (3rdparty/libzip/LICENSE)" "$SRC/3rdparty/libzip/LICENSE"
  notice "LZMA SDK (3rdparty/lzma/LICENSE.txt)" "$SRC/3rdparty/lzma/LICENSE.txt"
  notice "rcheevos (3rdparty/rcheevos/LICENSE)" "$SRC/3rdparty/rcheevos/LICENSE"
  notice "SimpleIni (3rdparty/simpleini/LICENCE.txt)" "$SRC/3rdparty/simpleini/LICENCE.txt"
  notice "SoundTouch, LGPL-2.1-or-later (3rdparty/soundtouch/COPYING.TXT)" "$SRC/3rdparty/soundtouch/COPYING.TXT"
  notice "GNU demangler, files under the LGPL-2.0-or-later (3rdparty/demangler/DemanglerLicenseLGPL.txt)" "$SRC/3rdparty/demangler/DemanglerLicenseLGPL.txt"
  header_notice "KISS FFT, inside FreeSurround (3rdparty/freesurround/src/kiss_fft.cpp)" "$SRC/3rdparty/freesurround/src/kiss_fft.cpp"
  notice "fast_float, used under MIT (3rdparty/fast_float/LICENSE-MIT)" "$SRC/3rdparty/fast_float/LICENSE-MIT"
  notice "RapidJSON (3rdparty/rapidjson/license.txt)" "$SRC/3rdparty/rapidjson/license.txt"
  header_notice "xxHash (3rdparty/include/xxhash.h)" "$SRC/3rdparty/include/xxhash.h"
  printf '\n===== ccc, the Chaos Compiler Collection (3rdparty/ccc) =====\n\n'
  echo "By chaoticgd, https://github.com/chaoticgd/ccc. Every file carries"
  echo "\"SPDX-License-Identifier: MIT\"; the tree has no licence file of its own. The MIT License:"
  echo
  cat <<'MIT'
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
MIT
  echo
  echo "Packed into pcsx2-wasm.data (/resources):"
  notice "Roboto (bin/resources/fonts/Roboto-Regular-copyright), Apache-2.0" "$SRC/bin/resources/fonts/Roboto-Regular-copyright"
  printf '\n===== Roboto Mono (bin/resources/fonts/RobotoMono-Medium.ttf), Apache-2.0 =====\n\n'
  echo "Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono),"
  echo "as the font's own name table says; licensed under the Apache License, Version 2.0. The tree"
  echo "carries no licence file for it."
  # The two Roboto notices point at the Apache-2.0 (the first at a Debian path a reader of this
  # file cannot open), so its text follows, from the copy in 3rdparty/fast_float, up to its end of
  # terms (fast_float's own boilerplate after that is left out).
  [ -f "$SRC/3rdparty/fast_float/LICENSE-APACHE" ] || { echo "notice: 3rdparty/fast_float/LICENSE-APACHE is missing" >&2; exit 1; }
  printf '\n===== The Apache License, Version 2.0 (for Roboto and Roboto Mono) =====\n\n'
  awk '{ print } /END OF TERMS AND CONDITIONS/ { exit }' "$SRC/3rdparty/fast_float/LICENSE-APACHE"
  notice "PromptFont (bin/resources/fonts/promptfont-license)" "$SRC/bin/resources/fonts/promptfont-license"
  printf '\n===== Font Awesome Free (bin/resources/fonts/fa-solid-900.ttf) =====\n\n'
  echo "Font Awesome 7 Free (Solid) by Fonticons, Inc., https://fontawesome.com; its fonts are under the SIL"
  echo "Open Font License 1.1 (the text is in the PromptFont notice above). The tree carries no licence file of its own."
  printf '\n===== SDL_GameControllerDB (bin/resources/game_controller_db.txt) =====\n\n'
  echo "From https://github.com/mdqinc/SDL_GameControllerDB, under the zlib licence (the text is in the"
  echo "SDL notice above, with SDL's copyright line)."
  echo
  echo "Emscripten $EMSCRIPTEN_VERSION: its runtime in pcsx2-wasm.js, its system libraries and the emdawnwebgpu port:"
  notice "Emscripten (LICENSE)" "$EM_ROOT/LICENSE"
  notice "musl libc (system/lib/libc/musl/COPYRIGHT)" "$EM_ROOT/system/lib/libc/musl/COPYRIGHT"
  notice "LLVM libc++, libc++abi, compiler-rt and libunwind (system/lib/libcxx/LICENSE.TXT)" "$EM_ROOT/system/lib/libcxx/LICENSE.TXT"
  notice "Dawn, emdawnwebgpu (webgpu/src/LICENSE)" "$DAWN/webgpu/src/LICENSE"
  notice "Dawn, emdawnwebgpu C++ headers (webgpu_cpp/LICENSE)" "$DAWN/webgpu_cpp/LICENSE"
} > "$OUT/LICENSE.notices.txt"

if [ "$OUT" -ef "$HERE/.." ]; then
  (cd "$HERE" && shasum -a 256 build.sh "${PATCHES[@]}" ../pcsx2-wasm.js ../pcsx2-wasm.wasm ../pcsx2-wasm.data ../disc-worker.js > SHA256SUMS)
  cat "$HERE/SHA256SUMS"
else
  (cd "$OUT" && shasum -a 256 pcsx2-wasm.js pcsx2-wasm.wasm pcsx2-wasm.data disc-worker.js > SHA256SUMS)
  cat "$OUT/SHA256SUMS"
fi
ls -l "$OUT"/pcsx2-wasm.*

# --- smoke test: the page with no BIOS and no disc -------------------------------
# TabStationToo's own: headless Chrome must reach the BIOS intake
# (body[data-state=nobios], runtime ready, cross-origin isolated, no console
# error, no request off the origin), once through the service worker (as
# GitHub Pages) and once with the isolation headers (as serve.py).
# Chrome is $CHROME (default /usr/bin/google-chrome); as root it needs
# --no-sandbox, which the CI passes too (a throwaway profile, this build only).
if [ "$SMOKE" = 1 ]; then
  SITE="$WORK/_site"
  python3 "$SRC/tools/wasm/assemble-site.py" --build-dir "$BUILD" --out "$SITE" --force
  CHROME_FLAGS=()
  [ "$(id -u)" = 0 ] && CHROME_FLAGS=(-- --no-sandbox)
  # ${a[@]+"${a[@]}"}: an empty array under set -u, which macOS's bash 3.2 calls unbound.
  node "$SRC/tools/wasm/smoke-test.mjs" --site "$SITE" ${CHROME_FLAGS[@]+"${CHROME_FLAGS[@]}"}
  node "$SRC/tools/wasm/smoke-test.mjs" --site "$SITE" --headers ${CHROME_FLAGS[@]+"${CHROME_FLAGS[@]}"}
fi
