#!/usr/bin/env bash
# Builds PlayAgain's Nintendo 3DS core: public/cores/panda3ds/panda3ds.{js,wasm}.
#
# Reproducible: the same commits and Emscripten give the same bytes. Panda3DS comes from `git archive` of the
# pinned commit, each submodule the browser core compiles from `git archive` of the commit Panda3DS pins (a plain
# tree, no .git), dynarmic (azahar-emu, the commit Panda3DS pins) with the two externals it builds the same way,
# and FAAD2 (the AAC decoder, GPL-2.0-or-later) from `git archive` of its 2.11.4 release into third_party/faad2.
# fdk-aac, which Panda3DS pins as a submodule, is never fetched: its licence is GPL-incompatible, and the script
# fails if any of its symbols reaches the link. Then three patches, all kept here so the build never needs
# another repository:
#   patches/panda3ds-emscripten.patch  Panda3DS for Emscripten and WebGL2   (both verbatim from gagarinyury/
#   patches/dynarmic-wasm32.patch      a WebAssembly backend for dynarmic    panda3ds-webxr @ 52a57e00, GPL-3.0+)
#   panda3ds-92e53d2-pa.patch          PlayAgain's (its header lists them): no SDL port, saves under the title ID,
#                                      FAAD2 for AAC, sound into a ring the page drains, WebGL-aligned vertex
#                                      fetch, the session clock and a fixed SSL seed
# and one file put in whole: include/fs/mii_data.hpp becomes the open Mii archive Azahar ships (mii.app.romfs.h, kept
# here verbatim), in place of Panda3DS's copy, which carries a Flaticon icon that may not be redistributed.
# Panda3DS's own CMake builds the core (AlberCore) and its libraries as static archives: dynarmic with the wasm
# JIT (guest ARM blocks become WebAssembly modules at run time), the OpenGL ES renderer, HLE audio, no Lua, no
# Vulkan/Metal, no Discord, no fastmem, no threads. PlayAgain's shim (pa_3ds.cpp, in place of the port's
# web_main.cpp) is compiled with the flags CMake used for the core and linked against all of them, for a page or
# (as it ships) a worker with an OffscreenCanvas, with WORKERFS for the game file. 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/panda3ds/source/build.sh
#
# Needs: git, cmake, ninja, patch, jq and a C++ compiler for Emscripten's tools. Emscripten is installed into
# EMSDK_DIR on first run. Takes about 5 minutes on a 10-core M4; the plain tree takes ~320 MB and the build
# ~160 MB beside the clones (KEEP_BUILD=0 deletes both at the end).
set -euo pipefail

PANDA3DS_COMMIT="92e53d26b898eb89d865f8407460900a88e7c0fa"   # wheremyfoodat/Panda3DS master, 2026-10-04 "Add Linux aarch64 build (#839)"
DYNARMIC_COMMIT="e77b1ba0b7da7cbe93021b01a663acfe7c4dd516"   # azahar-emu/dynarmic, 2026-06-24 (the one Panda3DS pins)
WEBXR_COMMIT="52a57e006416bbba997f8fd800af5bb868e93740"      # gagarinyury/panda3ds-webxr, 2026-10-18: where patches/ came from (not fetched)
FAAD2_COMMIT="e8e76f0a44db45aed773a3f62fe35a63c867a738"      # FreewareAdvancedAudio/faad2 (was knik0/faad2), tag 2.11.4, 2026-10-01
EMSCRIPTEN_VERSION="6.0.12"
# The Panda3DS submodules the browser core compiles or includes (no SDL2, LuaJIT, Qt, Discord, xbyak/oaknut, tests,
# and no fdk-aac: FAAD2 replaces it).
PANDA_SUBMODULES=(
  third_party/boost third_party/elfio third_party/hips third_party/httplib third_party/stb third_party/miniaudio
  third_party/mio third_party/fmt third_party/toml11 third_party/glm third_party/cmrc third_party/cryptopp/cryptopp
  third_party/capstone
)
# dynarmic's bundled externals that a wasm32 build uses (fmt comes from Panda3DS's tree).
DYNARMIC_SUBMODULES=(externals/mcl externals/robin-map)

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUT="$(cd "$HERE/.." && pwd)"
EMSDK_DIR="${EMSDK_DIR:-$HOME/.cache/playagain/emsdk}"
WORK="${WORK:-$HOME/.cache/playagain/panda3ds}"
JOBS="${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu)}"
PA_PATCH="$HERE/panda3ds-${PANDA3DS_COMMIT:0:7}-pa.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; }

# --- Panda3DS, dynarmic and their submodules at the pinned commits, as a plain tree ---
mkdir -p "$WORK"
if [ ! -d "$WORK/panda3ds-git/.git" ]; then
  git clone --quiet --filter=blob:none https://github.com/wheremyfoodat/Panda3DS.git "$WORK/panda3ds-git"
fi
if [ ! -d "$WORK/dynarmic-git/.git" ]; then
  git clone --quiet --filter=blob:none https://github.com/azahar-emu/dynarmic.git "$WORK/dynarmic-git"
fi
if [ ! -d "$WORK/faad2-git/.git" ]; then
  git clone --quiet --filter=blob:none https://github.com/FreewareAdvancedAudio/faad2.git "$WORK/faad2-git"
fi
git -C "$WORK/panda3ds-git" cat-file -e "$PANDA3DS_COMMIT^{commit}" 2>/dev/null || git -C "$WORK/panda3ds-git" fetch --quiet origin
git -C "$WORK/dynarmic-git" cat-file -e "$DYNARMIC_COMMIT^{commit}" 2>/dev/null || git -C "$WORK/dynarmic-git" fetch --quiet origin
git -C "$WORK/faad2-git" cat-file -e "$FAAD2_COMMIT^{commit}" 2>/dev/null || git -C "$WORK/faad2-git" fetch --quiet origin
[ "$(git -C "$WORK/panda3ds-git" ls-tree "$PANDA3DS_COMMIT" third_party/dynarmic | awk '{print $3}')" = "$DYNARMIC_COMMIT" ] \
  || { echo "Panda3DS $PANDA3DS_COMMIT does not pin dynarmic $DYNARMIC_COMMIT" >&2; exit 1; }
git -C "$WORK/panda3ds-git" -c advice.detachedHead=false checkout --quiet --force "$PANDA3DS_COMMIT"
git -C "$WORK/dynarmic-git" -c advice.detachedHead=false checkout --quiet --force "$DYNARMIC_COMMIT"
git -C "$WORK/panda3ds-git" submodule update --init --quiet --depth 1 -- "${PANDA_SUBMODULES[@]}"
git -C "$WORK/dynarmic-git" submodule update --init --quiet --depth 1 -- "${DYNARMIC_SUBMODULES[@]}"

SRC="$WORK/src"
BUILD="$WORK/build"
rm -rf "$SRC" "$BUILD"
mkdir -p "$SRC"
git -C "$WORK/panda3ds-git" archive --format=tar "$PANDA3DS_COMMIT" | tar -x -C "$SRC"
archive_submodule() { # <superproject> <commit there> <path> <destination under SRC>
  local pinned
  pinned="$(git -C "$1" ls-tree "$2" "$3" | awk '{print $3}')"
  rm -rf "${SRC:?}/$4"
  mkdir -p "$SRC/$4"
  git -C "$1/$3" archive --format=tar "$pinned" | tar -x -C "$SRC/$4"
}
for path in "${PANDA_SUBMODULES[@]}"; do
  archive_submodule "$WORK/panda3ds-git" "$PANDA3DS_COMMIT" "$path" "$path"
done
mkdir -p "$SRC/third_party/dynarmic"
git -C "$WORK/dynarmic-git" archive --format=tar "$DYNARMIC_COMMIT" | tar -x -C "$SRC/third_party/dynarmic"
for path in "${DYNARMIC_SUBMODULES[@]}"; do
  archive_submodule "$WORK/dynarmic-git" "$DYNARMIC_COMMIT" "$path" "third_party/dynarmic/$path"
done
rm -rf "$SRC/third_party/fdk-aac"   # the empty submodule folder git archive leaves
mkdir -p "$SRC/third_party/faad2"
git -C "$WORK/faad2-git" archive --format=tar "$FAAD2_COMMIT" | tar -x -C "$SRC/third_party/faad2"

patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch < "$HERE/patches/panda3ds-emscripten.patch"
patch -d "$SRC/third_party/dynarmic" -p1 --quiet --no-backup-if-mismatch < "$HERE/patches/dynarmic-wasm32.patch"
patch -d "$SRC" -p1 --quiet --no-backup-if-mismatch < "$PA_PATCH"

# --- the Mii data: the open archive, never Panda3DS's Flaticon icon ---
# Panda3DS's include/fs/mii_data.hpp is citra_system_archives' open Mii archive with one texture swapped for a red-panda
# icon from Flaticon (Panda3DS 5733b46), whose licence forbids redistribution. It is written over, whole, from
# mii.app.romfs.h: the same 73,600-byte archive as Azahar ships it (externals/open_source_archives/include/, git blob
# f5ee83e6a880a5d08b61b2b2caacac2a82b03bf9; made by the generator's Mii rebuilder at 5e6b5df, GPL-2.0-or-later), in the
# header's shape (a constexpr MII_DATA[]). A file put in rather than a patch hunk, so the icon's bytes are in nothing
# PlayAgain publishes.
{
  echo "#pragma once"
  echo ""
  echo "// PlayAgain (build.sh): the open Mii archive Azahar ships, externals/open_source_archives/include/mii.app.romfs.h"
  sed -e 's/^unsigned char MII_DATA\[\] = {$/constexpr unsigned char MII_DATA[] = {/' "$HERE/mii.app.romfs.h"
} > "$SRC/include/fs/mii_data.hpp"
grep -q '^constexpr unsigned char MII_DATA\[\] = {$' "$SRC/include/fs/mii_data.hpp" || { echo "mii.app.romfs.h is not the expected header" >&2; exit 1; }
if grep -qi flaticon "$SRC/include/fs/mii_data.hpp"; then echo "the Flaticon Mii data is still in the tree" >&2; exit 1; fi

# --- AlberCore and its libraries, single-threaded, static -----------------------
# The panda3ds-wasm port's options (its scripts/build-core.sh), plus the file-prefix maps so no path of this machine
# reaches the binary. Only the AlberCore target is built: the SDL frontend is not.
export SOURCE_DATE_EPOCH="$(git -C "$WORK/panda3ds-git" log -1 --format=%ct "$PANDA3DS_COMMIT")"
MAP="-ffile-prefix-map=$SRC=panda3ds -ffile-prefix-map=$BUILD=build -ffile-prefix-map=$HERE=pa"
emcmake cmake -S "$SRC" -B "$BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DENABLE_VULKAN=OFF -DENABLE_METAL=OFF -DENABLE_DISCORD_RPC=OFF -DENABLE_LUAJIT=OFF -DENABLE_RENDERDOC_API=OFF \
  -DENABLE_FASTMEM=OFF -DENABLE_GIT_VERSIONING=OFF -DENABLE_WAYLAND=OFF -DENABLE_HTTP_SERVER=OFF -DENABLE_TESTS=OFF \
  -DENABLE_OPENGL=ON -DOPENGL_PROFILE=OpenGLES -DDYNARMIC_USE_BUNDLED_EXTERNALS=ON \
  -DCMAKE_C_FLAGS="-Wno-everything $MAP" -DCMAKE_CXX_FLAGS="-Wno-everything $MAP" >/dev/null
cmake --build "$BUILD" --target AlberCore -j "$JOBS" >/dev/null

# --- fdk-aac must not reach the binary: nothing of it is fetched, built or defined in what is linked ---
NM="$EMSDK/upstream/bin/llvm-nm"
[ -x "$NM" ] || { echo "no llvm-nm at $NM" >&2; exit 1; }
if [ -e "$SRC/third_party/fdk-aac" ] || [ -n "$(cd "$BUILD" && find . -iname '*fdk*' -print -quit)" ]; then
  echo "fdk-aac is in the tree or the build" >&2; exit 1
fi
if (cd "$BUILD" && find . -name '*.a' -exec "$NM" -A --defined-only {} + 2>/dev/null) | grep -E ' (aacDecoder_|CAacDecoder|FDK|aacDecoder)' >&2; then
  echo "fdk-aac symbols are defined in the link inputs" >&2; exit 1
fi

# --- the shim, compiled as CMake compiled emulator.cpp, linked against every archive ---
# (wasm-ld resolves archive members in any order, so the sorted list is enough.)
CORE_CMD="$(jq -r '.[] | select(.file | endswith("/src/emulator.cpp")) | .command' "$BUILD/compile_commands.json")"
read -r -a CORE_ARGS <<< "$CORE_CMD"
SHIM_FLAGS=()
skip=0
for arg in "${CORE_ARGS[@]:1}"; do
  if [ "$skip" = 1 ]; then skip=0; continue; fi
  case "$arg" in
    -o|-c) skip=1 ;;
    *) SHIM_FLAGS+=("$arg") ;;
  esac
done
em++ "${SHIM_FLAGS[@]}" -c "$HERE/pa_3ds.cpp" -o "$BUILD/pa_3ds.o"
ARCHIVES=()
while IFS= read -r a; do ARCHIVES+=("$a"); done < <(cd "$BUILD" && find . -name '*.a' | LC_ALL=C sort)

EXPORTS="_main,_malloc,_free"
for f in init set_clock load title_id save_dir run_frame set_keys set_circle set_touch layout layout_rect read_audio audio_rate \
         screen frame_count ticks cpu_vertex_draws guest_clock gl_counter heap_reserve state_loaded; do
  EXPORTS="$EXPORTS,_pa_$f"
done
# The port's link options, minus its debugging extras: one thread, WebGL2 only, a 256 MB heap that may grow to 2 GB
# (the wasm JIT hands pointers to JavaScript as 32-bit ints), the file system with WORKERFS (the game file, mounted
# in the worker, read where the game asks), and OFFSCREENCANVAS_SUPPORT for the WebGL2 context on the worker's
# OffscreenCanvas (Module.canvas).
(cd "$BUILD" && em++ pa_3ds.o "${ARCHIVES[@]}" -O3 $MAP \
  -sMODULARIZE=1 -sEXPORT_NAME=createPanda3dsModule -sENVIRONMENT=web,worker \
  -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=268435456 -sMAXIMUM_MEMORY=2147483648 -sSTACK_SIZE=2097152 \
  -sFORCE_FILESYSTEM=1 -lworkerfs.js -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT=1 -sGL_TRACK_ERRORS=0 \
  -sEXPORTED_FUNCTIONS="$EXPORTS" \
  -sEXPORTED_RUNTIME_METHODS=FS,HEAPU8,HEAP16,HEAPF32,ENV,UTF8ToString,stringToUTF8,lengthBytesUTF8 \
  -o "$OUT/panda3ds.js")

# --- licences: Panda3DS is GPL-3.0 (version 3 only: its files grant no later version, and DuckStation's are taken
# under their GPL-3.0 option), the panda3ds-wasm patches GPL-3.0-or-later, dynarmic 0BSD, FAAD2 GPL-2.0-or-later; the
# notices of everything else linked in, as the trees carry them, then Emscripten's runtime and PlayAgain's own notes
# (NOTICES.playagain.txt: what the trees do not carry as files, from the licence audit of 2026-11-09).
cp "$SRC/LICENSE.md" "$OUT/LICENSE.panda3ds.txt"
{
  echo "Third-party notices for panda3ds.wasm, from the Panda3DS $PANDA3DS_COMMIT, dynarmic $DYNARMIC_COMMIT and FAAD2 $FAAD2_COMMIT source trees."
  echo "Code from FAAD2 is copyright (c) Nero AG, www.nero.com"
  for f in third_party/dynarmic/LICENSE.txt third_party/dynarmic/externals/mcl/LICENSE third_party/dynarmic/externals/robin-map/LICENSE \
           third_party/fmt/LICENSE third_party/toml11/LICENSE third_party/glm/copying.txt third_party/cmrc/LICENSE.txt \
           third_party/cryptopp/cryptopp/License.txt third_party/faad2/COPYING third_party/capstone/LICENSES/LICENSE.TXT \
           third_party/capstone/LICENSES/LICENSE_BSD_3_CLAUSE.txt third_party/capstone/LICENSES/LICENSE_LLVM.TXT \
           third_party/boost/LICENSE_1_0.txt third_party/elfio/LICENSE.txt third_party/miniaudio/LICENSE third_party/mio/LICENSE \
           third_party/stb/LICENSE third_party/teakra/LICENSE third_party/xxhash/LICENSE third_party/imgui/LICENSE.txt \
           third_party/hips/LICENSE.md third_party/result/LICENSE third_party/host_memory/LICENSE.txt; 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 third_party/cityhash/cityhash.cpp third_party/duckstation/gl/stream_buffer.cpp third_party/glad/src/gl.c \
           include/bitfield.hpp include/termcolor.hpp include/align.hpp third_party/duckstation/gl/stream_buffer.h \
           third_party/glad/include/KHR/khrplatform.h; do
    printf '\n===== %s (header) =====\n\n' "$f"
    awk 'NR <= 40 { print } /^$/ && NR > 3 { exit }' "$SRC/$f"
  done
  # The Emscripten runtime linked in: its own licence and musl's.
  for f in LICENSE system/lib/libc/musl/COPYRIGHT; do
    printf '\n===== Emscripten %s: %s =====\n\n' "$EMSCRIPTEN_VERSION" "$f"
    cat "$EMSDK_DIR/upstream/emscripten/$f"
  done
  cat "$HERE/NOTICES.playagain.txt"
} > "$OUT/LICENSE.notices.txt"
(cd "$HERE" && shasum -a 256 build.sh pa_3ds.cpp "$(basename "$PA_PATCH")" patches/dynarmic-wasm32.patch patches/panda3ds-emscripten.patch \
  mii.app.romfs.h NOTICES.playagain.txt ../panda3ds-worker.js ../panda3ds.js ../panda3ds.wasm > SHA256SUMS)
if [ "${KEEP_BUILD:-1}" = 0 ]; then rm -rf "$SRC" "$BUILD"; fi
ls -l "$OUT/panda3ds.js" "$OUT/panda3ds.wasm"
shasum -a 256 "$OUT/panda3ds.wasm"
