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

root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
fixture_root=$(mktemp -d)
trap 'rm -rf "${fixture_root}"' EXIT
fixture="${fixture_root}/mtran"

rsync -a \
  --exclude '.build/' \
  --exclude 'build/' \
  --exclude 'install/' \
  --exclude 'log/' \
  --exclude 'vendor/' \
  --exclude 'dependencies/tools/' \
  --exclude 'runtime/' \
  --exclude 'models/en_zh-Hans/' \
  "${root}/" "${fixture}/"

if [[ "${ROS_DISTRO:-}" != "humble" ]]; then
  echo "ROS2 Humble environment must be sourced before running this test" >&2
  exit 1
fi

if missing_output=$(cmake -S "${fixture}" -B "${fixture}/build-missing" 2>&1); then
  echo "CMake unexpectedly configured without prepared runtime files" >&2
  exit 1
fi
grep -Fq './dependencies/auto_install.sh' <<< "${missing_output}"
grep -Fq 'runtime/bin/mtranserver' <<< "${missing_output}"

mkdir -p "${fixture}/runtime/bin" \
  "${fixture}/runtime/config" \
  "${fixture}/models/en_zh-Hans"
printf '#!/usr/bin/env bash\nexit 0\n' > "${fixture}/runtime/bin/mtranserver"
chmod +x "${fixture}/runtime/bin/mtranserver"
printf '{"data":[]}\n' > "${fixture}/runtime/config/records.json"
for model_file in \
  model.enzh.intgemm.alphas.bin \
  lex.50.50.enzh.s2t.bin \
  srcvocab.enzh.spm \
  trgvocab.enzh.spm; do
  printf 'fixture\n' > "${fixture}/models/en_zh-Hans/${model_file}"
done

cmake -S "${fixture}" -B "${fixture}/build-ready" -DBUILD_TESTING=OFF >/dev/null

grep -Fq 'runtime/bin/mtranserver DESTINATION lib/${PROJECT_NAME}' "${fixture}/CMakeLists.txt"
grep -Fq 'models/en_zh-Hans DESTINATION share/${PROJECT_NAME}/models' "${fixture}/CMakeLists.txt"
grep -Fq 'runtime/config/records.json DESTINATION share/${PROJECT_NAME}/mtranserver_config' \
  "${fixture}/CMakeLists.txt"

printf 'CMake preparation tests passed\n'
