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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BOOST_ROOT="${BOOST_WASM_CACHE_DIR:-${ROOT_DIR}/.cache/toolchains/boost}"
DOWNLOAD_DIR="${BOOST_ROOT}/downloads"
SOURCE_DIR="${BOOST_ROOT}/src"
INSTALL_DIR="${BOOST_ROOT}/install-wasm"
ARCHIVE="${DOWNLOAD_DIR}/boost_1_83_0.tar.bz2"
DOWNLOAD_URL="${BOOST_DOWNLOAD_URL:-https://mirrors.aliyun.com/blfs/conglomeration/boost/boost_1_83_0.tar.bz2}"
EXPECTED_SHA256="6478edfe2f3305127cffe8caf73ea0176c53769f4bf1585be237eb30798c3b8e"
JOBS="${JOBS:-$(nproc)}"

if [[ "$(emcc --version | sed -n '1s/.* \([0-9][0-9.]*\) .*/\1/p')" != "3.1.69" ]]; then
  echo "Boost wasm SDK must use Emscripten 3.1.69." >&2
  exit 1
fi
mkdir -p "${DOWNLOAD_DIR}" "${SOURCE_DIR}" "${INSTALL_DIR}"
if [[ ! -f "${ARCHIVE}" ]]; then
  curl --fail --location --retry 3 --connect-timeout 15 --output "${ARCHIVE}.part" "${DOWNLOAD_URL}"
  mv "${ARCHIVE}.part" "${ARCHIVE}"
fi
[[ "$(sha256sum "${ARCHIVE}" | awk '{print $1}')" == "${EXPECTED_SHA256}" ]] || { echo "Boost 1.83.0 archive SHA-256 mismatch." >&2; exit 1; }
if [[ ! -x "${SOURCE_DIR}/bootstrap.sh" ]]; then
  tar -xjf "${ARCHIVE}" -C "${SOURCE_DIR}" --strip-components=1
fi
if [[ ! -x "${SOURCE_DIR}/b2" ]]; then
  (cd "${SOURCE_DIR}" && ./bootstrap.sh --with-libraries=program_options,regex,thread,date_time)
fi
cp -f "${ROOT_DIR}/scripts/boost-emscripten-compiler-wrapper.sh" "${SOURCE_DIR}/boost-emscripten-compiler-wrapper.sh"
chmod +x "${SOURCE_DIR}/boost-emscripten-compiler-wrapper.sh"
(cd "${SOURCE_DIR}" && ./b2 --user-config="${ROOT_DIR}/config/boost-emscripten-user-config.jam" \
  toolset=emscripten-3.1.69 link=static threading=multi variant=release \
  --with-program_options --with-regex --with-thread --with-date_time \
  --prefix="${INSTALL_DIR}" cxxflags=-pthread linkflags=-pthread install -j"${JOBS}")
for name in program_options regex thread date_time atomic; do
  cp -f "${INSTALL_DIR}/lib/libboost_${name}.bc" "${INSTALL_DIR}/lib/libboost_${name}.a"
done

cd "${ROOT_DIR}"
node --input-type=module - "${INSTALL_DIR}" <<'NODE'
import { inspectWasmStaticArchive } from './scripts/freecad-naming-sdk-lib.mjs'
const install = process.argv[2]
const archives = {}
for (const name of ['program_options', 'regex', 'thread', 'date_time', 'atomic']) {
  archives[name] = await inspectWasmStaticArchive(`${install}/lib/libboost_${name}.a`)
}
console.log(JSON.stringify({ status: 'boost-wasm-pass', version: '1.83.0', pthread: true, archives }, null, 2))
NODE
