#!/bin/sh
# Builds Taisei Project (https://github.com/taisei-project/taisei, MIT code,
# music and portraits CC BY 4.0) for the site, from upstream source with its
# own Emscripten build (misc/ci/emscripten-build.ini), with these changes
# (taisei.diff beside this script):
# - the game files aren't fetched one by one from data/ next to the page: the
#   play page downloads them in three zips (on R2, at /files/taisei/) and
#   writes each file to /res-cache under its content id, which the game's
#   resource index reads; a file it needs before its zip is in makes it wait
#   (Module.needFile tells the page which one, so that zip goes first);
# - nothing is kept in IndexedDB: the play page keeps the player's files
#   (/persistent/storage) as the game's save, and reaches the file system
#   through Module.wgFS (closure renames FS's own methods).
#
# The zips: start holds every file the game opened from its first start to
# the first stage (pack-start.txt beside this script, by resource path) and
# everything that isn't a later stage's or the ending's; stages23 holds
# stages 2 and 3, stages456 the rest. pack.py makes them.
#
# Needs git, python3 (with zstandard), meson 1.8 or newer, ninja, cmake,
# glslc, spirv-cross, gettext (msgfmt) and emsdk 4.0.7 (source emsdk_env.sh
# first).
# Usage: sh build.sh [work dir]
# Writes taisei.js and taisei.wasm next to this script, and the zips for R2
# to <work dir>/r2/taisei/ (upload them to wasmgame-files under the same
# keys). For a newer Taisei, copy this folder to taisei-<new rev>-p1 and
# change the revision below; a change to the build here takes the next -p
# number.
set -eu

TAISEI_REV=f4d3342226e915f369db8680688723adb18e4efa
EMSDK_VERSION=4.0.7

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

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

mkdir -p "$work"
if [ ! -d "$work/src" ]; then
  git clone -q https://github.com/taisei-project/taisei.git "$work/src"
fi
cd "$work/src"
git checkout -q -f $TAISEI_REV
git submodule update -q --init --recursive
git apply "$here/taisei.diff"

printf "[constants]\ntoolchain = '%s/'\n" "$(dirname "$(command -v emcc)")" > "$work/toolchain.ini"
rm -rf "$work/build" "$work/install"
meson setup "$work/build" \
  --cross-file misc/ci/common-options.ini --cross-file misc/ci/forcefallback.ini \
  --cross-file "$work/toolchain.ini" --cross-file misc/ci/emscripten-build.ini \
  --prefix="$work/install" -Ddocs=disabled -Dtests=disabled -Dwerror=false -Ddebug=false
ninja -C "$work/build"
meson install -C "$work/build"
cp "$work/install/taisei.js" "$work/install/taisei.wasm" "$here/"

python3 "$here/pack.py" "$work/build/resources/res-index.inc.h" "$work/install/data" "$here/pack-start.txt" "$work/r2/taisei"
ls -l "$work/r2/taisei"
