#!/usr/bin/env bash
set -euo pipefail

repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
camotics_dir="$repo_root/CAMotics"
cbang_dir="$repo_root/.cache/camotics-native/cbang"
cbang_revision="9b6672a0e2b800a909d799ffa3ab46774cf171b8"
jobs=${CAMOTICS_BUILD_JOBS:-$(nproc)}

test -f "$camotics_dir/SConstruct"
command -v git >/dev/null
command -v scons >/dev/null
command -v qmake >/dev/null
command -v moc >/dev/null
command -v uic >/dev/null
command -v lrelease >/dev/null
command -v pkg-config >/dev/null
python3 -c 'import six' >/dev/null
test -f /usr/include/v8/v8.h
pkg-config --exists Qt5Core Qt5Gui Qt5Widgets Qt5OpenGL Qt5Network Qt5WebSockets

if [[ ! -d "$cbang_dir/.git" ]]; then
  mkdir -p "$(dirname "$cbang_dir")"
  git clone --filter=blob:none https://github.com/CauldronDevelopmentLLC/cbang.git "$cbang_dir"
fi
current_revision=$(git -C "$cbang_dir" rev-parse HEAD)
if [[ "$current_revision" != "$cbang_revision" ]]; then
  git -C "$cbang_dir" fetch --depth=1 origin "$cbang_revision"
  git -C "$cbang_dir" checkout --detach "$cbang_revision"
fi
test "$(git -C "$cbang_dir" rev-parse HEAD)" = "$cbang_revision"
test -z "$(git -C "$cbang_dir" status --porcelain)"

export QT_SELECT=qt5
export CBANG_HOME="$cbang_dir"

# The Debian V8 package is built without pointer compression. Keep C! and the
# CAMotics embedder on the same ABI instead of relying on the host default.
cbang_build_marker="$repo_root/.cache/camotics-native/cbang-build-v8-noptr-cxx17"
if [[ ! -f "$cbang_build_marker" || "$(<"$cbang_build_marker")" != "$cbang_revision" || ! -f "$cbang_dir/lib/libcbang.a" ]]; then
  scons -C "$cbang_dir" strict=0 cxxstd=c++17 v8_compress_pointers=0 -j "$jobs"
  printf '%s\n' "$cbang_revision" > "$cbang_build_marker"
fi
scons -C "$camotics_dir" strict=0 cxxstd=c++17 v8_compress_pointers=0 \
  with_gui=1 with_tpl=1 camotics tplang gcodetool planner camsim build/camotics.so -j "$jobs"

"$camotics_dir/camotics" --version
"$camotics_dir/tplang" --version
sha256sum "$camotics_dir/camotics" "$camotics_dir/tplang"
