#!/bin/sh
# Builds Anarch (https://gitlab.com/drummyfish/anarch, CC0 1.0: code, levels,
# art, sounds and music) for the site, from upstream source with its SDL
# frontend (main_sdl.c), with these changes (anarch.diff beside this script):
# - it draws at 640x400 and 60 frames a second with the PC version's effects,
#   instead of the web version's 256x160 at 35;
# - the game's save (progress, settings and the saved position) is the file
#   /save/anarch.sav, which the play page fills before main() and reads back,
#   where the web version kept none;
# - the page passes the grabbed mouse's movement in (webMouse) to turn and
#   look, where the web version had no mouse look;
# - the Resume snapshot (webTakeSnapshot, webRestoreSnapshot) copies the
#   game's state in memory, and a run in a level comes back in the menu;
#   webOver says when the last level is won;
# - after a hidden tab the game's clock waits instead of running every
#   missed step at once, and mouse movement outside play is dropped;
# - SDL leaves game controllers to the page, which maps them to keys;
# - M opens the map as well as Tab;
# - it builds with newer Emscripten (emscripten.h declares the main loop).
# main() is run by the play page (INVOKE_RUN=0). The game's data is all in
# its source, so the .wasm is the whole game.
#
# Needs git and emsdk 4.0.7 (source emsdk_env.sh first).
# Usage: sh build.sh [work dir]
# Writes anarch.js and anarch.wasm next to this script.
# For a newer Anarch, copy this folder to anarch-<new rev>-p1 and change the
# revision below; a change to the build here takes the next -p number.
set -eu

ANARCH_REV=6f90562161200682459e772f1dacb747f23c5f95
EMSDK_VERSION=4.0.7

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

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

# Emscripten fetches SDL as a GitHub archive; clone it instead.
. "$here/ports.sh"
port sdl2 libsdl-org/SDL release-2.32.0 SDL-release-2.32.0 https://github.com/libsdl-org/SDL/archive/release-2.32.0.zip

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://gitlab.com/drummyfish/anarch.git "$src"
git -C "$src" -c advice.detachedHead=false checkout -q -f "$ANARCH_REV"
git -C "$src" apply "$here/anarch.diff"

emcc "$src/main_sdl.c" -o "$here/anarch.js" -O3 -std=c99 -w -sUSE_SDL=2 \
  -sINVOKE_RUN=0 -sFORCE_FILESYSTEM -sEXPORTED_RUNTIME_METHODS=FS,callMain,HEAPU8 \
  -sEXPORTED_FUNCTIONS=_main,_webMouse,_webSnapshotBuffer,_webSnapshotSize,_webTakeSnapshot,_webRestoreSnapshot,_webOver
