#!/bin/sh
# Builds Sandspiel (https://github.com/MaxBittker/sandspiel, MIT) for the site,
# from upstream source with sandspiel.diff beside this script, which:
# - takes out posting, browsing, likes and sign-in (they need sandspiel.club's
#   servers), its ads, analytics, error reporting and offline cache;
# - lays the board and the buttons out to fit the frame the play page puts
#   it in, with the buttons in one sideways-scrolling row when the frame is
#   narrow;
# - adds window.wg for the play page: the board as bytes (to save and load)
#   and pause.
# The Rust part is built with cargo and wasm-bindgen instead of wasm-pack,
# and the page with Sandspiel's own webpack setup, with the npm packages
# pinned by package-lock.json beside this script (and the crates by
# Cargo.lock).
#
# Needs git, a Rust toolchain with the wasm32-unknown-unknown target,
# wasm-bindgen-cli 0.2.129 (cargo install wasm-bindgen-cli --version 0.2.129)
# and Node 22.
# Usage: sh build.sh [work dir]
# Writes the page (sandspiel.html and its files) next to this script. The
# .wasm and chunk names change with the source: list them in the sandspiel
# entry of src/scripts/config.ts.
set -eu

SANDSPIEL_REV=9936e06b07a583aedfba9589c0cead2917f405fb

here=$(cd "$(dirname "$0")" && pwd)
work=${1:-${TMPDIR:-/tmp}/sandspiel-build}

if [ ! -d "$work/src" ]; then
  git clone -q https://github.com/MaxBittker/sandspiel.git "$work/src"
fi
cd "$work/src"
git checkout -q -f $SANDSPIEL_REV
git clean -q -fdx -e node_modules -e crate/target
git apply "$here/sandspiel.diff"
rm -f yarn.lock pnpm-lock.yaml
cp "$here/package-lock.json" .
cp "$here/Cargo.lock" crate/

cd crate
cargo build --locked --release --target wasm32-unknown-unknown
wasm-bindgen --target bundler --out-dir pkg target/wasm32-unknown-unknown/release/sandtable.wasm
printf '{\n  "name": "sandtable",\n  "module": "sandtable.js",\n  "sideEffects": ["./sandtable.js", "./snippets/*"]\n}\n' > pkg/package.json
cd ..

npm ci --no-audit --no-fund --legacy-peer-deps
npx --no-install webpack --mode=production
cd dist
# Not index.html: the site serves that at the folder name without its
# trailing slash, where the page's relative links point one folder up.
cp index.html "$here/sandspiel.html"
cp main.js styles.css ./*.wasm ./[0-9]*.js ./*.LICENSE.txt "$here/"
ls -l "$here"
