#!/usr/bin/env bash
# Builds PlayAgain's SameBoy core: public/cores/sameboy/sameboy.{js,wasm}.
#
# Reproducible: the same SameBoy commit, Emscripten and rgbds give the same
# bytes. The script refuses other versions. It writes SHA256SUMS beside
# itself (this folder's sources and the two outputs); record the wasm's
# SHA-256 in ../README.md. Run it twice and compare.
#
#   bash public/cores/sameboy/source/build.sh
#
# Needs: git, make, xxd and a C compiler. Emscripten is installed into
# EMSDK_DIR on first run; rgbds is built from its tag into RGBDS_DIR when the
# one on PATH is another version (that build needs bison and libpng).
set -euo pipefail

SAMEBOY_COMMIT="1e1d4ae575cb97f510880b238bae10ed40cf333d" # v1.0.4-28
EMSCRIPTEN_VERSION="6.0.12"
RGBDS_VERSION="1.0.4"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUT="$(cd "$HERE/.." && pwd)"
EMSDK_DIR="${EMSDK_DIR:-$HOME/.cache/playagain/emsdk}"
WORK="${WORK:-$HOME/.cache/playagain/sameboy}"
RGBDS_DIR="${RGBDS_DIR:-$HOME/.cache/playagain/rgbds}"

# --- 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; }
if ! { command -v rgbasm >/dev/null && rgbasm --version | grep -q "v$RGBDS_VERSION"; }; then
  if [ ! -x "$RGBDS_DIR/rgbasm" ]; then
    git clone --branch "v$RGBDS_VERSION" --depth 1 https://github.com/gbdev/rgbds.git "$RGBDS_DIR"
    make -C "$RGBDS_DIR" -j"$(getconf _NPROCESSORS_ONLN)" >/dev/null
  fi
  export PATH="$RGBDS_DIR:$PATH"
fi
rgbasm --version | grep -q "v$RGBDS_VERSION" || { echo "need rgbds $RGBDS_VERSION" >&2; exit 1; }

# --- SameBoy at the pinned commit, with its own open boot ROMs ---------------
if [ ! -d "$WORK/.git" ]; then
  git clone https://github.com/LIJI32/SameBoy.git "$WORK"
fi
git -C "$WORK" fetch --quiet origin
git -C "$WORK" checkout --quiet --force "$SAMEBOY_COMMIT"
make -C "$WORK" -j"$(getconf _NPROCESSORS_ONLN)" CONF=release \
  build/bin/BootROMs/dmg_boot.bin build/bin/BootROMs/cgb_boot_fast.bin build/bin/BootROMs/sgb_boot.bin >/dev/null

GEN="$WORK/pa-gen"
mkdir -p "$GEN"
{
  printf '#include <stddef.h>\n'
  # The CGB gets SameBoy's fast boot ROM (no animation to run unseen).
  for pair in dmg:dmg_boot cgb:cgb_boot_fast sgb:sgb_boot; do
    (cd "$WORK/build/bin/BootROMs" && xxd -i -n "pa_${pair%%:*}_boot" "${pair#*:}.bin") | sed 's/^unsigned/const unsigned/'
  done
} > "$GEN/bootroms.c"

CORE_FILES=(gb sgb apu memory mbc timing display camera sm83_cpu joypad save_state random rumble printer workboy)
SRC=("$HERE/pa_sameboy.c" "$GEN/bootroms.c")
for f in "${CORE_FILES[@]}"; do SRC+=("$WORK/Core/$f.c"); done

EXPORTS="_malloc,_free"
for f in init model load_rom reset skip_boot set_clock set_keys run_frame framebuffer screen_width screen_height \
         frame_rate set_audio read_audio battery_size save_battery load_battery state_size save_state load_state \
         rumble read write link set_render set_presented presented_framebuffer pair_power_on run_pair_frame \
         phase offset set_offset set_guard debug_shift pair_snapshot_size pair_snapshot pair_restore pair_restore_keep_clock \
         pair_digest cart_ram_ptr cart_ram_size; do
  EXPORTS="$EXPORTS,_pa_$f"
done

# --- compile -----------------------------------------------------------------
emcc "${SRC[@]}" \
  -I"$WORK" -include "$HERE/patime.h" \
  -std=gnu11 -D_GNU_SOURCE -DGB_INTERNAL -DGB_VERSION='"1.0.4-pa"' \
  -DGB_DISABLE_TIMEKEEPING -DGB_DISABLE_REWIND -DGB_DISABLE_DEBUGGER -DGB_DISABLE_CHEATS -DGB_DISABLE_CHEAT_SEARCH \
  -O3 -flto -DNDEBUG -fno-stack-protector -Wno-everything \
  -ffile-prefix-map="$WORK"=sameboy -ffile-prefix-map="$HERE"=pa \
  -sMODULARIZE=1 -sEXPORT_NAME=createSameboyModule -sENVIRONMENT=web \
  -sFILESYSTEM=0 -sMALLOC=emmalloc -sALLOW_MEMORY_GROWTH=1 \
  -sINITIAL_MEMORY=16777216 -sSTACK_SIZE=1048576 \
  -sEXPORTED_FUNCTIONS="$EXPORTS" -sEXPORTED_RUNTIME_METHODS=HEAPU8,HEAP16,HEAPU32 \
  -o "$OUT/sameboy.js"

cp "$WORK/LICENSE" "$OUT/LICENSE.sameboy.txt"
(cd "$HERE" && shasum -a 256 build.sh pa_sameboy.c patime.h ../sameboy.js ../sameboy.wasm > SHA256SUMS)
ls -l "$OUT/sameboy.js" "$OUT/sameboy.wasm"
shasum -a 256 "$OUT/sameboy.wasm"
