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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
YAML_ROOT="${YAML_CPP_WASM_CACHE_DIR:-${ROOT_DIR}/.cache/toolchains/yaml-cpp}"
YAML_SOURCE_DIR="${YAML_ROOT}/src"
YAML_BUILD_DIR="${YAML_ROOT}/build-wasm"
YAML_INSTALL_DIR="${YAML_ROOT}/install-wasm"
JOBS="${JOBS:-$(nproc)}"
LOCKED_COMMIT="f7320141120f720aecc4c32be25586e7da9eb978"

if [[ ! -f "${YAML_SOURCE_DIR}/CMakeLists.txt" ]]; then
  echo "yaml-cpp 0.8.0 source is missing: ${YAML_SOURCE_DIR}" >&2
  exit 1
fi
if [[ "$(git -C "${YAML_SOURCE_DIR}" rev-parse HEAD)" != "${LOCKED_COMMIT}" ]]; then
  echo "yaml-cpp source must be locked to ${LOCKED_COMMIT}." >&2
  exit 1
fi
if [[ -n "$(git -C "${YAML_SOURCE_DIR}" status --porcelain)" ]]; then
  echo "yaml-cpp source checkout must be clean." >&2
  exit 1
fi
if [[ "$(emcc --version | sed -n '1s/.* \([0-9][0-9.]*\) .*/\1/p')" != "3.1.69" ]]; then
  echo "yaml-cpp wasm SDK must use Emscripten 3.1.69." >&2
  exit 1
fi

emcmake cmake --fresh -S "${YAML_SOURCE_DIR}" -B "${YAML_BUILD_DIR}" -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_INSTALL_PREFIX="${YAML_INSTALL_DIR}" \
  -DYAML_BUILD_SHARED_LIBS=OFF \
  -DYAML_CPP_BUILD_TESTS=OFF \
  -DYAML_CPP_BUILD_TOOLS=OFF \
  -DYAML_CPP_INSTALL=ON \
  -DYAML_CPP_FORMAT_SOURCE=OFF
cmake --build "${YAML_BUILD_DIR}" --parallel "${JOBS}"
cmake --install "${YAML_BUILD_DIR}"

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