#!/bin/bash
# Compile the engine from source and install it under PREFIX (PREFIX/lib/sc-native/{starcraft,sc_selfcheck}).
#   build-engine.sh SOURCE_DIR PREFIX [LOG_FILE]
# The list of installed files goes to PREFIX/lib/sc-native/install-manifest.txt.
set -euo pipefail

src=$1
prefix=$2
log=${3:-}
build=$(mktemp -d "${TMPDIR:-/tmp}/sc-native-build.XXXXXX")
trap 'rm -rf "$build"' EXIT
[ -n "$log" ] || log="$build/build.log"
: > "$log"

run() {  # run a build step, output to the log; on failure show the end of the log
    if ! "$@" >> "$log" 2>&1; then
        echo "  FAILED: $*" >&2
        echo "  ---- last lines of $log ----" >&2
        tail -n 30 "$log" >&2
        return 1
    fi
}

jobs=$(nproc 2>/dev/null || echo 2)
# Each compile job of the bigger files can use ~1 GB; stay within the machine's memory.
mem_gb=$(awk '/MemAvailable/ { printf "%d", $2 / 1048576 }' /proc/meminfo 2>/dev/null || echo 2)
[ "$mem_gb" -ge 1 ] || mem_gb=1
[ "$jobs" -le "$mem_gb" ] || jobs=$mem_gb

generator=()
command -v ninja >/dev/null && generator=(-G Ninja)

echo "  configuring (cmake)..."
run cmake -S "$src" -B "$build" "${generator[@]}" -DCMAKE_BUILD_TYPE=Release -DSC_BUILD_TOOLS=OFF \
    -DCMAKE_INSTALL_PREFIX="$prefix"
grep -q "SDL2 not found" "$log" && { echo "  FAILED: SDL2 development files not found (libsdl2-dev)" >&2; exit 1; }
echo "  compiling with $jobs parallel jobs (takes a few minutes)..."
start=$(date +%s)
run cmake --build "$build" --parallel "$jobs"
echo "  compiled in $(( $(date +%s) - start )) s"
run cmake --install "$build"
mkdir -p "$prefix/lib/sc-native"
# CMake writes the manifest without a final newline; one path per line for `while read`.
{ cat "$build/install_manifest.txt"; echo; } | sed '/^$/d' > "$prefix/lib/sc-native/install-manifest.txt"
