#!/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

# Some filesystems the repo might be checked out on (e.g. a VirtualBox
# vboxsf shared folder) refuse to create symlinks at all ("Operation not
# permitted"), which plain `cp -a` needs for SDL2/SDL2_mixer's
# libFoo.so -> libFoo.so.N -> libFoo.so.N.M dev-symlink chain. Detect
# that up front, once, and copy real file content instead of recreating
# links if so, rather than failing partway through. `-a` implies
# --preserve=all (which includes hard-link relationships between files,
# not just symlinks - SDL2's install hard-links the two most-specific
# version files together), so --no-preserve=links is needed alongside
# --dereference to avoid that too.
CP_FLAGS=(-a)
if ! ln -s test-target build_ext/.symlink-test 2>/dev/null; then
    echo "(destination filesystem doesn't support symlinks - copying real file content instead)"
    CP_FLAGS=(-a --dereference --no-preserve=links)
else
    rm -f build_ext/.symlink-test
fi

cp "${CP_FLAGS[@]}" /opt/prebuilt/built_sdl build_ext/
cp "${CP_FLAGS[@]}" /opt/prebuilt/built_sdl_mixer build_ext/
cp "${CP_FLAGS[@]}" /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 "${CP_FLAGS[@]}" {} "$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"
