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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
FREECAD_SOURCE_DIR="${FREECAD_SOURCE_DIR:-${ROOT_DIR}/.cache/freecad/FreeCAD}"
PLANEGCS_SOURCE_DIR="${FREECAD_SOURCE_DIR}/src/Mod/Sketcher/App/planegcs"
DIST_DIR="${PLANEGCS_DIST_DIR:-${ROOT_DIR}/native/planegcs/dist}"
PUBLIC_DIR="${PLANEGCS_PUBLIC_DIR:-${ROOT_DIR}/public/native/planegcs}"
HOST_HEADERS_DIR="${ROOT_DIR}/.cache/bitbybit/planegcs-host-headers"
OFFLINE_HEADERS_DIR="${ROOT_DIR}/.cache/offline-sysroot/include"
BOOST_INCLUDE_DIR="${BOOST_INCLUDE_DIR:-$([[ -d "${OFFLINE_HEADERS_DIR}/boost" ]] && printf '%s' "${OFFLINE_HEADERS_DIR}" || printf '%s' /usr/include)}"
EIGEN3_INCLUDE_DIR="${EIGEN3_INCLUDE_DIR:-$([[ -d "${OFFLINE_HEADERS_DIR}/eigen3" ]] && printf '%s' "${OFFLINE_HEADERS_DIR}/eigen3" || printf '%s' /usr/include/eigen3)}"

if [[ ! -f "${PLANEGCS_SOURCE_DIR}/GCS.cpp" ]]; then
  echo "Locked FreeCAD planegcs source not found: ${PLANEGCS_SOURCE_DIR}" >&2
  exit 1
fi
if ! command -v em++ >/dev/null; then
  echo "Emscripten em++ is required." >&2
  exit 1
fi
if [[ ! -d "${EIGEN3_INCLUDE_DIR}" ]] || [[ ! -d "${BOOST_INCLUDE_DIR}/boost" ]]; then
  echo "Eigen3 and Boost headers are required." >&2
  exit 1
fi

mkdir -p "${DIST_DIR}" "${PUBLIC_DIR}" "${HOST_HEADERS_DIR}"
if [[ -L "${HOST_HEADERS_DIR}/boost" && "$(readlink "${HOST_HEADERS_DIR}/boost")" != "${BOOST_INCLUDE_DIR}/boost" ]]; then
  rm "${HOST_HEADERS_DIR}/boost"
fi
if [[ ! -e "${HOST_HEADERS_DIR}/boost" ]]; then
  ln -s "${BOOST_INCLUDE_DIR}/boost" "${HOST_HEADERS_DIR}/boost"
fi
em++ \
  "${PLANEGCS_SOURCE_DIR}/Geo.cpp" \
  "${PLANEGCS_SOURCE_DIR}/Constraints.cpp" \
  "${PLANEGCS_SOURCE_DIR}/SubSystem.cpp" \
  "${PLANEGCS_SOURCE_DIR}/qp_eq.cpp" \
  "${PLANEGCS_SOURCE_DIR}/GCS.cpp" \
  "${ROOT_DIR}/native/planegcs/planegcs_bindings.cpp" \
  -I"${ROOT_DIR}/native/planegcs/stubs" \
  -I"${FREECAD_SOURCE_DIR}/src" \
  -I"${PLANEGCS_SOURCE_DIR}" \
  -I"${HOST_HEADERS_DIR}" \
  -I"${EIGEN3_INCLUDE_DIR}" \
  -std=c++20 -O2 -DNDEBUG -DEIGEN_NO_DEBUG -fexceptions -pthread --bind \
  -sMODULARIZE=1 -sEXPORT_ES6=1 -sENVIRONMENT=web,worker,node \
  -sPTHREAD_POOL_SIZE=2 \
  -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=16777216 -sMAXIMUM_MEMORY=536870912 \
  -sNO_EXIT_RUNTIME=1 \
  -o "${DIST_DIR}/freecad-planegcs.js"

# Emscripten output contains a version-sensitive trailing-space-only line.
# Normalize it before copying and hashing so native and public artifacts stay
# byte-identical across a clean rebuild.
perl -pi -e 's/[ \t]+$//' "${DIST_DIR}/freecad-planegcs.js"

cp "${ROOT_DIR}/native/planegcs/package.json" "${DIST_DIR}/package.json"
cp "${DIST_DIR}/freecad-planegcs.js" "${PUBLIC_DIR}/freecad-planegcs.js"
cp "${DIST_DIR}/freecad-planegcs.wasm" "${PUBLIC_DIR}/freecad-planegcs.wasm"
sha256sum "${DIST_DIR}/freecad-planegcs.js" "${DIST_DIR}/freecad-planegcs.wasm"
