#!/usr/bin/env bash
# Rebuilds the Genesis Plus GX core beside this folder (public/cores/genplusgx/):
#   bash public/cores/genplusgx/source/build.sh
#
# Run this when bumping the core; the output is committed, so day-to-day
# development never needs Emscripten. This script is published with the
# core (linked from /licenses) as the recipe for the shipped binary.
#
# Requires: emsdk (https://github.com/emscripten-core/emsdk) and Python 3.10+.
#   git clone https://github.com/emscripten-core/emsdk && cd emsdk
#   EMSDK_PYTHON=$(which python3.12) ./emsdk install latest && ./emsdk activate latest
#   source ./emsdk_env.sh
set -euo pipefail

UPSTREAM_COMMIT="2d7131c5efa606f649d36e1685a8ca47c24f31b3"
OUT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="${WORK:-$(mktemp -d)}"

command -v emcc >/dev/null || { echo "emcc not on PATH — source emsdk_env.sh first"; exit 1; }

git clone https://github.com/libretro/Genesis-Plus-GX.git "$WORK/src"
git -C "$WORK/src" checkout "$UPSTREAM_COMMIT"
cd "$WORK/src"

# The emscripten target sets STATIC_LINKING=1, which EXCLUDES libretro-common
# because RetroArch normally supplies it. We are building a standalone core,
# so the archive is built that way and the missing sources are added at link
# time below — otherwise wasm-ld fails on rfseek/rftell and friends.
emmake make -f Makefile.libretro platform=emscripten -j"$(sysctl -n hw.ncpu 2>/dev/null || nproc)"
cp genesis_plus_gx_libretro_emscripten.bc libgenplusgx.a   # it IS an ar archive

LC=libretro/libretro-common
emcc libgenplusgx.a \
  $LC/streams/file_stream.c $LC/streams/file_stream_transforms.c \
  $LC/compat/fopen_utf8.c $LC/compat/compat_snprintf.c $LC/compat/compat_strl.c \
  $LC/compat/compat_strcasestr.c $LC/compat/compat_posix_string.c \
  $LC/encodings/encoding_utf.c $LC/file/file_path.c $LC/file/retro_dirent.c \
  $LC/lists/string_list.c $LC/lists/dir_list.c $LC/memmap/memalign.c \
  $LC/string/stdstring.c $LC/vfs/vfs_implementation.c \
  -I$LC/include -Ilibretro -Icore \
  -o "$OUT/genplusgx.js" \
  -O3 -sENVIRONMENT=web -sMODULARIZE=1 -sEXPORT_NAME=createGenPlusGxModule \
  -sALLOW_MEMORY_GROWTH=1 -sALLOW_TABLE_GROWTH=1 -sINITIAL_MEMORY=64MB -sFILESYSTEM=1 \
  -sEXPORTED_FUNCTIONS='["_malloc","_free","_retro_init","_retro_deinit","_retro_api_version","_retro_get_system_info","_retro_get_system_av_info","_retro_set_environment","_retro_set_video_refresh","_retro_set_audio_sample","_retro_set_audio_sample_batch","_retro_set_input_poll","_retro_set_input_state","_retro_set_controller_port_device","_retro_reset","_retro_run","_retro_serialize_size","_retro_serialize","_retro_unserialize","_retro_load_game","_retro_unload_game","_retro_get_region","_retro_get_memory_data","_retro_get_memory_size"]' \
  -sEXPORTED_RUNTIME_METHODS='["addFunction","removeFunction","getValue","setValue","FS","HEAPU8","HEAP16","HEAP32","HEAPF32"]'

cp LICENSE.txt "$OUT/LICENSE.genesis-plus-gx.txt"
echo "built -> $OUT"
