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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
XERCES_ROOT="${XERCES_C_WASM_CACHE_DIR:-${ROOT_DIR}/.cache/toolchains/xerces-c}"
DOWNLOAD_DIR="${XERCES_ROOT}/downloads"
SOURCE_DIR="${XERCES_ROOT}/src"
BUILD_DIR="${XERCES_ROOT}/build-wasm"
INSTALL_DIR="${XERCES_ROOT}/install-wasm"
ICU_ROOT="${ICU_WASM_CACHE_DIR:-${ROOT_DIR}/.cache/toolchains/icu}"
ARCHIVE="${DOWNLOAD_DIR}/xerces-c-3.2.4.tar.xz"
DOWNLOAD_URL="${XERCES_C_DOWNLOAD_URL:-https://archive.apache.org/dist/xerces/c/3/sources/xerces-c-3.2.4.tar.xz}"
EXPECTED_SHA256="075bc57940da0f9be6dd183c550c8ce0b9833e4550dc382048377a1a5e3b2bd9"
JOBS="${JOBS:-$(nproc)}"

if [[ "$(emcc --version | sed -n '1s/.* \([0-9][0-9.]*\) .*/\1/p')" != "3.1.69" ]]; then
  echo "Xerces-C wasm SDK must use Emscripten 3.1.69." >&2
  exit 1
fi
for archive in libicuuc.a libicudata.a; do
  if [[ ! -f "${ICU_ROOT}/install-wasm/lib/${archive}" ]]; then
    echo "Xerces-C wasm SDK requires the staged ICU archive: ${archive}" >&2
    exit 1
  fi
done
mkdir -p "${DOWNLOAD_DIR}" "${SOURCE_DIR}" "${BUILD_DIR}" "${INSTALL_DIR}/lib"
if [[ ! -f "${ARCHIVE}" ]]; then
  curl --fail --location --retry 3 --connect-timeout 15 --output "${ARCHIVE}.part" "${DOWNLOAD_URL}"
  mv "${ARCHIVE}.part" "${ARCHIVE}"
fi
if [[ "$(sha256sum "${ARCHIVE}" | awk '{print $1}')" != "${EXPECTED_SHA256}" ]]; then
  echo "Xerces-C 3.2.4 archive SHA-256 mismatch." >&2
  exit 1
fi
if [[ ! -f "${SOURCE_DIR}/CMakeLists.txt" ]]; then
  tar -xJf "${ARCHIVE}" -C "${SOURCE_DIR}" --strip-components=1
fi

emcmake cmake --fresh -S "${SOURCE_DIR}" -B "${BUILD_DIR}" -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_INSTALL_PREFIX="${INSTALL_DIR}" \
  -DBUILD_SHARED_LIBS=OFF \
  -Dnetwork=OFF \
  -Dtranscoder=icu \
  -Dmsgloader=inmemory \
  -Dthreads=ON \
  -Dsse2=OFF \
  -DICU_ROOT="${ICU_ROOT}/install-wasm" \
  -DICU_INCLUDE_DIR="${ICU_ROOT}/install-wasm/include" \
  -DICU_UC_LIBRARY_RELEASE="${ICU_ROOT}/install-wasm/lib/libicuuc.a" \
  -DICU_DATA_LIBRARY_RELEASE="${ICU_ROOT}/install-wasm/lib/libicudata.a"
cmake --build "${BUILD_DIR}" --target xerces-c --parallel "${JOBS}"
# Upstream assigns samples and the core library to the same runtime component.
# Install development files separately and stage the already-built archive directly.
cmake --install "${BUILD_DIR}" --component development
cp -f "${BUILD_DIR}/src/libxerces-c.a" "${INSTALL_DIR}/lib/libxerces-c.a"

cd "${ROOT_DIR}"
node --input-type=module - "${INSTALL_DIR}" <<'NODE'
import { inspectWasmStaticArchive } from './scripts/freecad-naming-sdk-lib.mjs'
const install = process.argv[2]
console.log(JSON.stringify({
  status: 'xerces-c-wasm-pass',
  version: '3.2.4',
  archive: await inspectWasmStaticArchive(`${install}/lib/libxerces-c.a`),
}, null, 2))
NODE
