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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
QT_ROOT="${QT6_WASM_CACHE_DIR:-${ROOT_DIR}/.cache/toolchains/qt6}"
QT_SOURCE_DIR="${QT_ROOT}/src"
QT_BUILD_DIR="${QT_ROOT}/build-wasm-freecad"
QT_INSTALL_DIR="${QT_ROOT}/install-wasm-freecad"
EMSDK_SHIM_DIR="${QT_ROOT}/emsdk-shim"
JOBS="${JOBS:-$(nproc)}"

if [[ ! -x "${QT_SOURCE_DIR}/configure" ]]; then
  echo "Qt 6.8.2 source is missing; run build:qt6-wasm-core or restore the offline Qt source first." >&2
  exit 1
fi
if ! command -v emcc >/dev/null || ! command -v em++ >/dev/null; then
  echo "Emscripten emcc/em++ are required." >&2
  exit 1
fi
if [[ "$(emcc --version | sed -n '1s/.* \([0-9][0-9.]*\) .*/\1/p')" != "3.1.69" ]]; then
  echo "FreeCAD Qt wasm SDK must use Emscripten 3.1.69." >&2
  exit 1
fi

mkdir -p "${QT_BUILD_DIR}" "${QT_INSTALL_DIR}"
if [[ ! -f "${QT_BUILD_DIR}/build.ninja" ]]; then
  (
    cd "${QT_BUILD_DIR}"
    EMSDK="${EMSDK_SHIM_DIR}" "${QT_SOURCE_DIR}/configure" \
      -platform wasm-emscripten \
      -qt-host-path /usr \
      -prefix /qt \
      -extprefix "${QT_INSTALL_DIR}" \
      -static -release -optimize-size \
      -feature-thread \
      -no-gui -no-widgets -no-dbus \
      -nomake examples -nomake tests -nomake benchmarks -nomake manual-tests \
      -no-pch -no-sbom \
      -- -G Ninja \
      -DCMAKE_TOOLCHAIN_FILE=/usr/share/emscripten/cmake/Modules/Platform/Emscripten.cmake \
      -DCMAKE_BUILD_TYPE=Release \
      -DQT_BUILD_TOOLS_WHEN_CROSSCOMPILING=OFF \
      -DQT_FEATURE_wasm_simd128=OFF \
      -DQT_FEATURE_wasm_exceptions=OFF \
      -DQt6HostInfo_DIR=/usr/lib/x86_64-linux-gnu/cmake/Qt6HostInfo
  )
fi
if ! rg -q '^QT_FEATURE_thread:INTERNAL=ON$' "${QT_BUILD_DIR}/CMakeCache.txt"; then
  echo "Existing FreeCAD Qt wasm build does not enable thread support: ${QT_BUILD_DIR}" >&2
  exit 1
fi

cmake --build "${QT_BUILD_DIR}" --target Core Concurrent Network Xml QTlsBackendCertOnlyPlugin QTlsBackendCertOnlyPlugin_init --parallel "${JOBS}"
cmake --install "${QT_BUILD_DIR}" --component Devel
for module in corelib concurrent network xml; do cmake --install "${QT_BUILD_DIR}/src/${module}"; done
cmake --install "${QT_BUILD_DIR}/src/plugins/tls/certonly"
mkdir -p "${QT_INSTALL_DIR}/mkspecs/common"
cmake -E copy_directory "${QT_SOURCE_DIR}/mkspecs/wasm-emscripten" "${QT_INSTALL_DIR}/mkspecs/wasm-emscripten"
cmake -E copy_directory "${QT_SOURCE_DIR}/mkspecs/common/wasm" "${QT_INSTALL_DIR}/mkspecs/common/wasm"
for helper in QtFeatureCommon.cmake "${QT_SOURCE_DIR}"/cmake/QtPublic*.cmake; do
  cp -f "${QT_SOURCE_DIR}/cmake/${helper##*/}" "${QT_INSTALL_DIR}/lib/cmake/Qt6/${helper##*/}"
done
for library in Core Concurrent Network Xml BundledPcre2 BundledZLIB; do
  cp -f "${QT_BUILD_DIR}/lib/libQt6${library}.a" "${QT_INSTALL_DIR}/lib/libQt6${library}.a"
done

node --input-type=module - "${ROOT_DIR}" "${QT_INSTALL_DIR}" <<'NODE'
import { inspectWasmStaticArchive } from './scripts/freecad-naming-sdk-lib.mjs'
const install = process.argv[3]
const result = {}
for (const name of ['Core', 'Concurrent', 'Network', 'Xml', 'BundledPcre2', 'BundledZLIB']) {
  result[name] = await inspectWasmStaticArchive(`${install}/lib/libQt6${name}.a`)
}
console.log(JSON.stringify({ status: 'qt6-freecad-wasm-pass', threadSupport: true, mkspec: `${install}/mkspecs/wasm-emscripten`, modules: result }, null, 2))
NODE
