#!/bin/sh
# Builds doom-wasm (https://github.com/cloudflare/doom-wasm, Chocolate Doom,
# GPL-2.0) for the site, from upstream source with its own build settings,
# plus snapshot.diff from this folder: two functions the play page calls
# between frames to keep and load a Resume snapshot (a savegame in slot 7,
# which the menus don't show). Source maps and debug info are left out.
#
# Needs git, autoconf, automake, make, pkg-config and emsdk 2.0.20 (source
# emsdk_env.sh first). Where github.com archive downloads are blocked, clone
# emscripten-ports SDL2 (version_23), SDL2_mixer (release-2.0.2), SDL2_net
# (version_2), ogg and vorbis (version_1) into one folder and pass it as
# PORTS=<folder>; emsdk 2.0.20's ogg, vorbis, sdl2_mixer and sdl2_net port
# files then need a SUBDIR line (e.g. SUBDIR = 'Ogg-' + TAG) to be overridden.
# Usage: sh build.sh [work dir]
# Writes websockets-doom.js and websockets-doom.wasm next to this script.
set -eu

DOOM_REV=65e0d3ae2ffa604155eebd96ed40da6567bd08f4
EMSDK_VERSION=2.0.20

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

case "$(emcc --version | head -1)" in
  *" $EMSDK_VERSION"*) ;;
  *) echo "warning: built and tested with emsdk $EMSDK_VERSION" >&2 ;;
esac
if [ -n "${PORTS:-}" ]; then
  export EMCC_LOCAL_PORTS="sdl2=$PORTS/SDL2,sdl2_mixer=$PORTS/SDL2_mixer,sdl2_net=$PORTS/SDL2_net,ogg=$PORTS/ogg,vorbis=$PORTS/vorbis"
fi

if [ ! -d "$work" ]; then
  git clone https://github.com/cloudflare/doom-wasm.git "$work"
fi
cd "$work"
git checkout -q -f $DOOM_REV
git apply "$here/snapshot.diff"
# no source map; -g0 also drops the debug info the compile flags' -g adds
sed -i 's/-gsource-map /-g0 /; s/ --source-map-base \///' configure.ac

emconfigure autoreconf -fi
ac_cv_exeext=".html" emconfigure ./configure --host=none-none-none
emmake make clean
emmake make

cp src/websockets-doom.js src/websockets-doom.wasm "$here/"
