#!/usr/bin/env bash
# Builds PlayAgain's Nintendo 64 core: public/cores/n64/n64.{js,wasm}.
#
# The core is the N64Wasm tree (nbarkhina/N64Wasm: mupen64plus-core with the
# cached interpreter, Glide64 and Rice on WebGL2, RSP-HLE, cxd4, no libco, no
# threads, no BIOS) at one pinned commit, patched by n64wasm-<sha7>.patch and
# driven by PlayAgain's shim (pa_n64.c) instead of its mymain.cpp. Nothing from
# Emscripten's ports is used: SDL is gone and zlib is the tree's own copy.
# Angrylion (HAVE_THR_AL) is left out: the tree carries no licence text for it.
#
# Reproducible: the same commit, patch and Emscripten give the same bytes.
# N64Wasm comes from `git archive` of the pinned commit (a plain tree, no
# .git). 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/n64/source/build.sh
#
# Needs: git, tar, patch, xargs and awk. Emscripten is installed into
# EMSDK_DIR on first run.
set -euo pipefail
export LC_ALL=C # the source and object lists are sorted, and link order is in the bytes

N64WASM_COMMIT="bfac222f8a27287022844b47000328531834e9c1" # master, 2025-02-10
EMSCRIPTEN_VERSION="6.0.12"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUT="$(cd "$HERE/.." && pwd)"
EMSDK_DIR="${EMSDK_DIR:-$HOME/.cache/playagain/emsdk}"
WORK="${WORK:-$HOME/.cache/playagain/n64}"
JOBS="${JOBS:-$(getconf _NPROCESSORS_ONLN)}"

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

# --- N64Wasm at the pinned commit, as a plain tree, patched ------------------
mkdir -p "$WORK"
if [ ! -d "$WORK/git/.git" ]; then
  git clone --quiet https://github.com/nbarkhina/N64Wasm.git "$WORK/git"
fi
git -C "$WORK/git" cat-file -e "$N64WASM_COMMIT^{commit}" 2>/dev/null || git -C "$WORK/git" fetch --quiet origin
SRC="$WORK/src"
BUILD="$WORK/build"
rm -rf "$SRC" "$BUILD"
mkdir -p "$SRC" "$BUILD"
git -C "$WORK/git" archive --format=tar "$N64WASM_COMMIT" code LICENSE | tar -x -C "$SRC"
patch -s -p1 -d "$SRC" < "$HERE/n64wasm-${N64WASM_COMMIT:0:7}.patch"
CODE="$SRC/code"

# --- sources: the Makefile's list, minus what the host now owns ---------------
# Out: mymain.cpp (SDL, keyboard, joysticks, fonts, menu: the shim replaces it),
# minizip (only mymain unpacked assets), Angrylion (no licence text in the
# tree) and get_time_using_C_localtime.c (the shim's session clock replaces it).
# In: the tree's zlib (libretronew.c's unused neil_serialize names gz*; the
# link drops it) and the shim.
mapfile -t FILES < <(grep -oE '(src|minizip)/[A-Za-z0-9_./-]+\.(c|cpp)' "$CODE/Makefile" \
  | grep -vE '^minizip/|^src/mupen64plus-video-angrylion/|/get_time_using_C_localtime\.c$' | sort -u)
mapfile -t ZLIB < <(cd "$CODE" && printf '%s\n' zlib/*.c | sort)
FILES+=("${ZLIB[@]}")

# The Makefile's defines (NOSSE: no SIMD; NO_LIBCO: one retro_run is one VI),
# without HAVE_THR_AL. -ffile-prefix-map keeps build paths out of the binary.
DEFINES="-D__LIBRETRO__ -DM64P_PLUGIN_API -DM64P_CORE_PROTOTYPES -D_ENDUSER_RELEASE -DNO_LIBCO -DNO_ASM -DNOSSE \
  -DHAVE_OPENGLES -DHAVE_OPENGLES2 -DHAVE_GLIDE64 -DHAVE_RICE -DSINC_LOWER_QUALITY -DDISABLE_3POINT -DNDEBUG -DINLINE=inline"
INCLUDES=""
for d in . src/glide2gl/src/Glide64 src/gles2rice/src src/mupen64plus-core/src src/mupen64plus-core/src/api src/include \
         src/mupen64plus-core/src/plugin/audio_libretro src/libretro-common/include src/libretro zlib; do
  INCLUDES="$INCLUDES -I$CODE/$d"
done
export CFLAGS="-O3 -flto -fno-stack-protector -Wno-everything -Wno-c++11-narrowing \
  -ffile-prefix-map=$CODE=n64wasm -ffile-prefix-map=$HERE=pa $DEFINES $INCLUDES"
export CODE BUILD

# --- compile, one object per source, in parallel -----------------------------
compile_one() {
  local src="$1" obj="$BUILD/${1%.*}.o"
  mkdir -p "$(dirname "$obj")"
  # shellcheck disable=SC2086
  (cd "$CODE" && emcc -c "$src" -o "$obj" $CFLAGS)
}
export -f compile_one
printf '%s\n' "${FILES[@]}" | xargs -P "$JOBS" -I{} bash -c 'compile_one "$@"' _ {}
# shellcheck disable=SC2086
(cd "$HERE" && emcc -c pa_n64.c -o "$BUILD/pa_n64.o" $CFLAGS)

mapfile -t OBJS < <(cd "$BUILD" && find . -name '*.o' | sed 's#^\./##' | sort)

# --- link ----------------------------------------------------------------------
EXPORTS="_malloc,_free"
for f in init set_renderer load_rom run_frame reset set_pad set_axes set_present set_clock \
         frame_rate screen_width screen_height audio_ring audio_ring_len audio_write_pos audio_rate \
         state_size save_state load_state save_ram_ptr save_ram_size save_ram_dirty rdram_ptr digest set_gpu_readback; do
  EXPORTS="$EXPORTS,_pa_$f"
done
(cd "$BUILD" && em++ "${OBJS[@]}" -O3 -flto -lGL \
  -sMODULARIZE=1 -sEXPORT_NAME=createN64Module -sENVIRONMENT=web,worker \
  -sFILESYSTEM=0 -sMALLOC=emmalloc -sINITIAL_MEMORY=536870912 -sALLOW_MEMORY_GROWTH=0 -sSTACK_SIZE=4194304 \
  -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sFULL_ES3=1 -sOFFSCREENCANVAS_SUPPORT=1 \
  -sEXPORTED_FUNCTIONS="$EXPORTS" -sEXPORTED_RUNTIME_METHODS=HEAPU8,HEAP16,HEAPU32 \
  -o "$OUT/n64.js")

# --- licences beside the binary -------------------------------------------------
# The whole is GPL-2.0-or-later (mupen64plus-core, Glide64, Rice, RSP-HLE);
# N64Wasm's own code is MIT, cxd4 is CC0; the notices file collects the
# permissive notices that must travel with a binary (libretro-common's MIT,
# X-Scale's BSD for the CIC-6105 code) and the zlib-style ones beside them.
cp "$SRC/LICENSE" "$OUT/LICENSE.n64wasm.txt"
cp "$CODE/src/mupen64plus-core/LICENSES" "$OUT/LICENSE.mupen64plus.txt"
cp "$CODE/src/mupen64plus-core/doc/gpl-license" "$OUT/LICENSE.gpl.txt"
cp "$CODE/src/mupen64plus-rsp-cxd4/COPYING" "$OUT/LICENSE.cxd4-cc0.txt"
{
  echo "Notices for the permissively licensed parts of PlayAgain's N64 core (n64.wasm),"
  echo "as they stand in N64Wasm $N64WASM_COMMIT (code/...)."
  for f in src/libretro-common/glsm/glsm.c src/mupen64plus-core/src/si/n64_cic_nus_6105.c \
           src/libretro/brumme_crc.c src/mupen64plus-core/src/main/md5.c zlib/zlib.h; do
    printf '\n==== code/%s\n\n' "$f"
    case "$f" in
      *n64_cic_nus_6105.c) awk 'NR==1,/of X-Scale\./' "$CODE/$f" ;;
      *) awk 'NR==1,/\*\//' "$CODE/$f" ;;
    esac
  done
} > "$OUT/LICENSE.notices.txt"

(cd "$HERE" && shasum -a 256 build.sh "n64wasm-${N64WASM_COMMIT:0:7}.patch" pa_n64.c ../n64.js ../n64.wasm > SHA256SUMS)
ls -l "$OUT/n64.js" "$OUT/n64.wasm"
shasum -a 256 "$OUT/n64.wasm"
