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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ICU_ROOT="${ICU_WASM_CACHE_DIR:-${ROOT_DIR}/.cache/toolchains/icu}"
ICU_DOWNLOAD_DIR="${ICU_ROOT}/downloads"
ICU_SOURCE_DIR="${ICU_ROOT}/src"
ICU_INSTALL_DIR="${ICU_ROOT}/install-wasm"
EM_CACHE_DIR="${ROOT_DIR}/.cache/toolchains/emscripten-freecad-cache"
ARCHIVE="${ICU_DOWNLOAD_DIR}/icu4c-68_2-src.tgz"
DOWNLOAD_URL="${ICU_DOWNLOAD_URL:-https://mirrors.aliyun.com/blfs/conglomeration/icu/icu4c-68_2-src.tgz}"
EXPECTED_MD5="c21cbdfe31a1e325afe765a16f907d20"
EXPECTED_SHA256="c79193dee3907a2199b8296a93b52c5cb74332c26f3d167269487680d479d625"
PORT_URL="https://github.com/unicode-org/icu/releases/download/release-68-2/icu4c-68_2-src.zip"

if [[ "$(emcc --version | sed -n '1s/.* \([0-9][0-9.]*\) .*/\1/p')" != "3.1.69" ]]; then
  echo "ICU wasm SDK must use Emscripten 3.1.69." >&2
  exit 1
fi
mkdir -p "${ICU_DOWNLOAD_DIR}" "${ICU_SOURCE_DIR}" "${ICU_INSTALL_DIR}/include" "${ICU_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 [[ "$(md5sum "${ARCHIVE}" | awk '{print $1}')" != "${EXPECTED_MD5}" ]]; then
  echo "ICU 68.2 archive MD5 mismatch." >&2
  exit 1
fi
if [[ "$(sha256sum "${ARCHIVE}" | awk '{print $1}')" != "${EXPECTED_SHA256}" ]]; then
  echo "ICU 68.2 archive SHA-256 mismatch." >&2
  exit 1
fi
if [[ ! -f "${ICU_SOURCE_DIR}/source/common/unicode/utypes.h" ]]; then
  tar -xzf "${ARCHIVE}" -C "${ICU_SOURCE_DIR}" --strip-components=1
fi

mkdir -p "${EM_CACHE_DIR}/ports/icu/icu"
cp -a "${ICU_SOURCE_DIR}/." "${EM_CACHE_DIR}/ports/icu/icu/"
printf '%s\n' "${PORT_URL}" > "${EM_CACHE_DIR}/ports/icu/.emscripten_url"
EM_FROZEN_CACHE=0 EM_CACHE="${EM_CACHE_DIR}" em++ -xc++ /dev/null -pthread -sUSE_ICU=1 -o "${ICU_ROOT}/icu-port-smoke.js"

cp -a "${EM_CACHE_DIR}/sysroot/include/unicode" "${ICU_INSTALL_DIR}/include/"
cp -f "${EM_CACHE_DIR}/sysroot/lib/wasm32-emscripten/libicu_common-mt.a" "${ICU_INSTALL_DIR}/lib/libicuuc.a"
cp -f "${EM_CACHE_DIR}/sysroot/lib/wasm32-emscripten/libicu_i18n-mt.a" "${ICU_INSTALL_DIR}/lib/libicui18n.a"
cp -f "${EM_CACHE_DIR}/sysroot/lib/wasm32-emscripten/libicu_stubdata-mt.a" "${ICU_INSTALL_DIR}/lib/libicudata.a"
cp -f "${EM_CACHE_DIR}/sysroot/lib/wasm32-emscripten/libicu_io-mt.a" "${ICU_INSTALL_DIR}/lib/libicuio.a"

cd "${ROOT_DIR}"
node --input-type=module - "${ICU_INSTALL_DIR}" <<'NODE'
import { inspectWasmStaticArchive } from './scripts/freecad-naming-sdk-lib.mjs'
const install = process.argv[2]
const archives = {}
for (const name of ['icuuc', 'icui18n', 'icudata', 'icuio']) {
  archives[name] = await inspectWasmStaticArchive(`${install}/lib/lib${name}.a`)
}
console.log(JSON.stringify({ status: 'icu-wasm-pass', version: '68.2', pthread: true, archives }, null, 2))
NODE
