#!/usr/bin/env bash
# Compiles engine/ (the vendored Shockolate snapshot) against the
# dependencies prebuilt into this image at /opt/prebuilt - no network
# access needed. Must be run with the repo root as the working directory
# - either via ../run-image.sh (which docker-runs this image with the
# repo bind-mounted at /workspace and WORKDIR set there), or directly
# when already inside this image (e.g. a CI job using this image as its
# container - see the Makefile's `engine` target, which picks whichever
# of these applies).
#
# Output lands in engine/.build-output/: the systemshock binary, the
# shared libraries it needs at runtime (lib/), and a default MIDI
# soundfont - everything the root Makefile needs to assemble dist/.
set -euo pipefail

REPO_ROOT="$(pwd)"
ENGINE_DIR="$REPO_ROOT/engine"
OUT_DIR="$ENGINE_DIR/.build-output"

cd "$ENGINE_DIR"

echo "== Wiring up prebuilt SDL2/SDL2_mixer/fluidsynth-lite from the image =="
rm -rf build_ext
mkdir -p build_ext
cp -a /opt/prebuilt/built_sdl build_ext/
cp -a /opt/prebuilt/built_sdl_mixer build_ext/
cp -a /opt/prebuilt/fluidsynth-lite build_ext/

echo "== Configuring (CMake, BUNDLED SDL2/SDL2_mixer/FluidSynth) =="
rm -f CMakeCache.txt
cmake -DENABLE_SDL2=BUNDLED -DENABLE_SOUND=BUNDLED -DENABLE_FLUIDSYNTH=BUNDLED .

echo "== Compiling =="
make -j"$(nproc)" systemshock

echo "== Assembling engine/.build-output =="
rm -rf "$OUT_DIR"
mkdir -p "$OUT_DIR/lib"
cp systemshock "$OUT_DIR/"
find build_ext/built_sdl/lib build_ext/built_sdl_mixer/lib build_ext/fluidsynth-lite/src \
    -name '*.so*' -not -name '*.la' -exec cp -a {} "$OUT_DIR/lib/" \;
cp /opt/prebuilt/soundfont/default.sf2 "$OUT_DIR/soundfont.sf2"

echo "== Done =="
echo "Binary:    $OUT_DIR/systemshock"
echo "Libraries: $OUT_DIR/lib/"
echo "Soundfont: $OUT_DIR/soundfont.sf2"
