#!/bin/sh
# Builds puzzles from Simon Tatham's Portable Puzzle Collection
# (https://www.chiark.greenend.org.uk/~sgtatham/puzzles/, MIT) for the site,
# from upstream source with its own Emscripten front end (emcc.c, emccpre.js,
# emcclib.js) and these changes (puzzles.diff beside this script):
# - no alert boxes: a fatal error goes to the play page's error screen and
#   other messages are kept for it;
# - a finger works as a mouse: a tap clicks, a drag drags, and a finger held
#   still for a moment presses the right button;
# - the menus, buttons and links of upstream's page are left out (the play
#   page's setup screen picks the puzzle's size), so the front end no longer
#   needs them;
# - window.wg for the play page: the game as a saved-game file (for saves
#   and Resume), new games with given parameters, the parameters of the game
#   in progress, whether it is solved, and pause; N and Q (new game, quit)
#   are left to the page;
# - the .wasm the play page has downloaded is taken from it (puzzleWasm)
#   instead of fetched again.
# Each puzzle runs in puzzle.html beside this script, which stands in for
# upstream's html/jspage.pl page: puzzle.html?net loads net.js and net.wasm.
#
# Needs git, cmake, make and emsdk 4.0.7 (source emsdk_env.sh first).
# Usage: sh build.sh [work dir]
# Writes <puzzle>.js and <puzzle>.wasm next to this script for the puzzles
# listed below. For a newer revision, copy this folder to
# puzzles-<new rev>-p1 and change the revision below; a change to the build
# here takes the next -p number.
set -eu

PUZZLES_REV=616da16f25da428ccda805536209095bd062676e
EMSDK_VERSION=4.0.7
PUZZLES="net untangle loopy bridges pattern lightup"

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

case "$(emcc --version | head -1)" in
  *" $EMSDK_VERSION "*) ;;
  *) echo "warning: built and tested with emsdk $EMSDK_VERSION" >&2 ;;
esac

mkdir -p "$work"
# A checkout left by an earlier build is reset, so this folder's diff is the one applied.
[ -d "$src" ] || git clone -q https://git.tartarus.org/simon/puzzles.git "$src"
git -C "$src" -c advice.detachedHead=false checkout -q -f "$PUZZLES_REV"
git -C "$src" clean -q -fdx
git -C "$src" apply "$here/puzzles.diff"

emcmake cmake -S "$src" -B "$work/build" -DCMAKE_BUILD_TYPE=Release -DMIN_CHROME_VERSION=85
# shellcheck disable=SC2086
cmake --build "$work/build" -j4 --target $PUZZLES
for p in $PUZZLES; do
  cp "$work/build/$p.js" "$work/build/$p.wasm" "$here/"
done
ls -l "$here"
