#!/usr/bin/env bash
# build.sh: PlayAgain's GameCube/Wii core = the Remenby31/wasm-dolphin fork's
# dolphin_web_core, built locally from source with the fork's own pinned recipe
# (npm script build:core:repro, run with plain node; the fork has no npm dependencies),
# first as the fork has it (steps 1-5, checked against the recorded hashes), then with
# PlayAgain's patch series (step 6): that second build is the core PlayAgain serves, and
# its files are checked against SHA256SUMS beside this script.
#
# Checked 2026-11-09 on the Mac mini M4 (darwin-arm64), Emscripten 5.0.7:
#   two clean builds (different checkout paths, fresh CMake trees, fresh Naga target,
#   fresh Emscripten cache for the second) gave byte-identical files:
#     dolphin-core-upstream.wasm  13,252,213 B  sha256 c3052959eafaca89eb3ac262a5a6503922f3623e8db3304cbee5db37959f1718
#     dolphin-core-upstream.js       291,463 B  sha256 3b07a61d6c781078f3aaa2a5e96d36cddca59745c92f8166897e5b276f46a91d
#   The fork's CI core at this commit (built on linux-x64) is d23ff1e5...; the .js is identical,
#   the .wasm differs only in the Rust (Naga + std) part, whose layout depends on the build host.
#
# Keys: Dolphin's built-in keys stay as upstream ships them (owner's option C). Nothing is added.
# Licence of the output: GPL-3.0-or-later (GPL-2.0-or-later Dolphin + Apache-2.0-only mbedTLS 2.28.0,
# SPIRV-Tools and two Naga crates). Never link it into a binary with the non-commercial cores.
set -euo pipefail
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)   # before any cd: the script may be called by a relative path

FORK_REPO=https://github.com/Remenby31/wasm-dolphin.git
# 50f0c362 = the sources of S3's core d23ff1e5 (Dolphin e22551ea + the fork's 150 locked patches).
# The fork's HEAD (37095160, 2026-11-09) adds harness-only counters (patches 0219, 0220) and a new core.
FORK_COMMIT=50f0c362eace59be859c138d785d256db6396a68
EXPECT_WASM_SHA256=c3052959eafaca89eb3ac262a5a6503922f3623e8db3304cbee5db37959f1718   # darwin-arm64 only
EXPECT_JS_SHA256=3b07a61d6c781078f3aaa2a5e96d36cddca59745c92f8166897e5b276f46a91d
RUSTUP_INIT_URL=https://static.rust-lang.org/rustup/dist/aarch64-apple-darwin/rustup-init
RUSTUP_INIT_SHA256=63752a1919a3a4793173ec70f8f212621a7ce38ba6a246095984482f4de20f9f      # rustup 1.29.3

DW=${DW:-$HOME/.cache/playagain/dolphin-web}   # outside every repo
SRC=${SRC:-$DW/wasm-dolphin}
JOBS=${JOBS:-8}
PLATFORM=darwin-arm64

export RUSTUP_HOME="$DW/rustup" CARGO_HOME="$DW/cargo" WASM_TOOLCHAIN_DIR="$DW/toolchain"
export PATH="$CARGO_HOME/bin:$PATH" PYTHONDONTWRITEBYTECODE=1
# verify:toolchain refuses these; make sure none leaks in from the shell.
unset EM_CONFIG EM_LLVM_ROOT EM_BINARYEN_ROOT EMCC_CFLAGS RUSTFLAGS CARGO_ENCODED_RUSTFLAGS RUSTC_WRAPPER || true

sha256() { shasum -a 256 "$1" | cut -d' ' -f1; }
mkdir -p "$DW/dl"

# 1. rustup, once, into $DW (no PATH or shell-profile edits). The fork's bootstrap needs it.
if [ ! -x "$CARGO_HOME/bin/rustup" ]; then
  curl -fsSL -o "$DW/dl/rustup-init" "$RUSTUP_INIT_URL"
  [ "$(sha256 "$DW/dl/rustup-init")" = "$RUSTUP_INIT_SHA256" ] || { echo "rustup-init hash mismatch" >&2; exit 1; }
  chmod +x "$DW/dl/rustup-init"
  "$DW/dl/rustup-init" -y --no-modify-path --default-toolchain none --profile minimal
fi

# 2. The fork at the pin, shallow, clean.
if [ ! -d "$SRC/.git" ]; then
  git init -q "$SRC"
  git -C "$SRC" remote add origin "$FORK_REPO"
fi
git -C "$SRC" fetch -q --depth 1 origin "$FORK_COMMIT"
git -C "$SRC" -c advice.detachedHead=false checkout -q --detach "$FORK_COMMIT"
[ -z "$(git -C "$SRC" status --porcelain)" ] || { echo "$SRC is not clean" >&2; exit 1; }
cd "$SRC"

# 3. Pinned toolchain (provenance/wasm-toolchain.lock.json, posix block) into $WASM_TOOLCHAIN_DIR:
#    emsdk bafd64c -> emsdk install 5.0.7 (= emscripten-releases 6cd98e86; compiler 263db4cf),
#    Rust nightly-2026-05-15 (rustc 7c3c88f4) + rust-src + wasm32-unknown-emscripten,
#    CMake 4.3.2 and Ninja 1.13.0 wheels with --require-hashes, ccache 4.14.1 by hash.
#    A separate emsdk: never install into ~/.cache/playagain/emsdk (6.0.12, other cores use it).
bash tools/toolchain/bootstrap.sh
node tools/verify-wasm-toolchain.mjs          # fails closed on any binary-hash mismatch

# 4. Fetch Dolphin e22551ea + submodules (+ SPIRV-Tools/Headers), verify it, apply the 150
#    locked patches, configure (CMake/Ninja via emcmake), build Naga (cargo --locked) and the
#    target dolphin_web_core, then compare with the committed core (writes parity.json).
#    No --install: cores/dolphin in the checkout keeps the fork's committed core.
#    ~11 min clean on the M4 (sources 216 s, configure 173 s, compile+LTO link 287 s), peak ~1.6 GB disk
#    (vendor/ 1.2 GB, CMake tree 0.15 GB, Naga target 0.26 GB) plus the 2.6 GB toolchain.
node tools/build-core-repro.mjs --jobs "$JOBS"

# 5. Check the result.
OUT="$SRC/build/repro/$PLATFORM/core"
[ "$(sha256 "$OUT/dolphin-core-upstream.js")" = "$EXPECT_JS_SHA256" ] || { echo "js differs" >&2; exit 1; }
if [ "$(sha256 "$OUT/dolphin-core-upstream.wasm")" != "$EXPECT_WASM_SHA256" ]; then
  echo "wasm differs from the recorded $PLATFORM build: $(sha256 "$OUT/dolphin-core-upstream.wasm")" >&2
  exit 1
fi
echo "OK (the fork's own core): $OUT"

# 6. PlayAgain's patch series (patches/, applied by apply.sh), then the same build again without
#    re-syncing the sources. ~1 min on the M4. The result is the served core.
if [ "${FORK_ONLY:-0}" != 1 ]; then
  bash "$HERE/apply.sh" "$SRC"
  node tools/build-core-repro.mjs --no-sync --allow-dirty --jobs "$JOBS"
  for f in dolphin-core-upstream.wasm dolphin-core-upstream.js; do
    want=$(grep " $f\$" "$HERE/SHA256SUMS" | cut -d' ' -f1)
    [ "$(sha256 "$OUT/$f")" = "$want" ] || { echo "$f differs from SHA256SUMS: $(sha256 "$OUT/$f")" >&2; exit 1; }
  done
  echo "OK (PlayAgain's core, as served): $OUT"
fi

# ---------------------------------------------------------------------------------------
# Optional: Emscripten 6.0.12 (PlayAgain's standard). Builds and runs with no source change;
# only the toolchain lock is re-recorded, in a separate checkout (the fork's documented
# "deliberate toolchain change" path), against a read-only symlink to the shared 6.0.12 SDK
# and a private EM_CACHE so nothing is written into ~/.cache/playagain/emsdk.
# Result 2026-11-09: 13,288,366 B, sha256 741c642814e5e138c5f7f34bf08d81f3ccd0b2ea90627128976dadeba6263883
# (one build; not yet checked twice).
if [ "${WITH_EM6:-0}" = 1 ]; then
  E6="$DW/wasm-dolphin-e6"
  [ -d "$E6/.git" ] || git clone -q --no-hardlinks "$SRC" "$E6"
  git -C "$E6" -c advice.detachedHead=false checkout -q --detach "$FORK_COMMIT"
  [ -e "$E6/vendor" ] || ln -s ../wasm-dolphin/vendor "$E6/vendor"
  mkdir -p "$DW/toolchain-6" "$DW/em-cache-6"
  ln -sfn "$HOME/.cache/playagain/emsdk" "$DW/toolchain-6/emsdk"
  ln -sfn "$DW/toolchain/python" "$DW/toolchain-6/python"
  export WASM_TOOLCHAIN_DIR="$DW/toolchain-6" EM_CACHE="$DW/em-cache-6"
  (cd "$E6" && git checkout -q -- provenance/wasm-toolchain.lock.json && node -e '
    const fs = require("fs"); const p = "provenance/wasm-toolchain.lock.json";
    const l = JSON.parse(fs.readFileSync(p, "utf8"));
    l.emscripten.version = "6.0.12";
    l.emscripten.compilerCommit = "5488e0871d46d19a3209988190fa6a653126256f";
    l.emscripten.emsdkCommit = l.posix.emsdk.commit = "d7b4130688bfa348392b921ab04015aa15c4f154";
    l.posix.emsdk.releasesHash = "6e9f6885cb17a3d6c8fd488a5cff730f50aba61d";
    delete l.posix.emscriptenTreeSha256;
    fs.writeFileSync(p, JSON.stringify(l, null, 2) + "\n");' \
   && node tools/toolchain/record.mjs --write >/dev/null \
   && node tools/verify-wasm-toolchain.mjs \
   && node tools/build-core-repro.mjs --jobs "$JOBS" --allow-dirty)
fi
