#!/usr/bin/env bash
# Configure + build Xenia Canary inside the container.
#
# The build directory is $XENIA_BUILD_DIR (outside the bind-mounted repo) on
# purpose. The host builds this same tree, and CMake caches an absolute compiler
# path and a generator: sharing repo/build between host and container makes each
# one reconfigure and relink everything the other just did.
#
# Parallelism comes from $SYLPH_JOBS, which the entrypoint derives from
# AVAILABLE MEMORY as well as core count — a full-parallel build of this tree
# has OOM-killed the host outright.
#
#   build-canary [Release|Debug]  [extra cmake --build args]
set -euo pipefail

CONFIG="${1:-Release}"; shift || true
SRC="${PROJECT_DIR:-/work}/xenia-canary"
BUILD="${XENIA_BUILD_DIR:-/sylph-home/re/canary-build}"
JOBS="${SYLPH_JOBS:-2}"

[ -d "$SRC" ] || { echo "build-canary: no source at $SRC" >&2; exit 1; }

# Submodules: this tree has drifted before, and a checkout that changes a
# gitlink fails silently into a half-built third_party. Report rather than fix,
# because one submodule here carries an in-tree cmake build whose untracked
# artifacts block an update.
if ! git -C "$SRC" submodule status --recursive 2>/dev/null | grep -qv '^ '; then
  :
else
  echo "build-canary: note — submodules are not all at their recorded commits:" >&2
  git -C "$SRC" submodule status 2>/dev/null | grep -v '^ ' | sed 's/^/  /' >&2
fi

if [ ! -f "$BUILD/CMakeCache.txt" ]; then
  echo "==> configuring $BUILD ($CONFIG, Ninja Multi-Config, clang $(clang --version | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+'))"
  cmake -S "$SRC" -B "$BUILD" -G "Ninja Multi-Config" \
    -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
    -DXENIA_BUILD_TESTS=OFF -DXENIA_BUILD_MISC=OFF \
    -DXENIA_ENABLE_LTO=OFF
fi

echo "==> building $CONFIG with -j$JOBS"
cmake --build "$BUILD" --config "$CONFIG" --parallel "$JOBS" --target xenia_canary "$@"

BIN="$BUILD/bin/Linux/$CONFIG/xenia_canary"
if [ -x "$BIN" ]; then
  echo "==> $BIN"
  echo "    run it with:  run-canary"
else
  echo "build-canary: target did not produce $BIN" >&2
  exit 1
fi
