#!/usr/bin/env bash
# Runs inside the emscripten/emsdk container (see ../build-wasm.sh).
# Builds pdfTeX (with SyncTeX) and BibTeX from the official TeX Live source tree to WebAssembly.
#
#   /src/texlive-source-<ver>.tar.gz   (mounted read-only)
#   /out                               (results: pdftex.{js,wasm}, bibtex.{js,wasm}, native tools)
#
# Two stages, as TeX Live's README.2building section 4.6 describes for cross builds:
#   1. native build: tangle/ctangle/otangle/tie (and a native pdftex for checks)
#   2. emscripten cross build (--host=wasm32-unknown-emscripten), with the native tools on PATH
set -euo pipefail

TL_VER="${TL_VER:?}"
JOBS="$(nproc)"
B=/build
mkdir -p "$B" /out
cd "$B"

if [ ! -d src ]; then
  mkdir src
  tar xzf "/src/texlive-source-${TL_VER}.tar.gz" -C src --strip-components=1
fi
# libs/luajit is configured even when no LuaJIT engine is built, and its native sub-configure fails
# under emconfigure ("did not find pow()"). Nothing we build needs it.
rm -rf src/libs/luajit

COMMON_FLAGS=(
  --disable-all-pkgs --enable-web2c
  --enable-pdftex --enable-pdftex-synctex
  --disable-synctex          # the synctex CLI tool; the engine still writes .synctex.gz
  --disable-tex --disable-etex --disable-ptex --disable-eptex --disable-uptex --disable-euptex
  --disable-aleph --disable-luatex --disable-luajittex --disable-luahbtex --disable-luajithbtex
  --disable-xetex --disable-mf --disable-mf-nowin --disable-mflua --disable-mfluajit
  --disable-mp --disable-pmp --disable-upmp --disable-hitex --disable-texprof
  --disable-ipc
  --disable-mktexmf-default --disable-mktexpk-default --disable-mktextfm-default
  --disable-mktexfmt-default
  --disable-shared --enable-static
  --disable-multiplatform --disable-native-texlive-build
  --without-x
  --without-system-zlib --without-system-libpng --without-system-xpdf
  --without-system-kpathsea --without-system-ptexenc --without-system-teckit
  --enable-dump-share
)

# ---------- stage 1: native ----------
if [ ! -x "$B/native-bin/tangle" ]; then
  mkdir -p native && cd native
  ../src/configure "${COMMON_FLAGS[@]}" > configure.log 2>&1 || { tail -40 configure.log; exit 1; }
  make -j"$JOBS" > make.log 2>&1 || { grep -n -i "error" make.log | tail -30; exit 1; }
  mkdir -p "$B/native-bin"
  for t in tangle ctangle otangle tie pdftex bibtex; do
    if [ -x texk/web2c/$t ]; then cp texk/web2c/$t "$B/native-bin/"; fi
  done
  cd "$B"
fi
ls "$B/native-bin"
export PATH="$B/native-bin:$PATH"

# ---------- stage 2: wasm ----------
# OTANGLE is only used for Aleph/XeTeX, which we do not build, but configure insists on one.
BUILD_TRIPLE="$(gcc -dumpmachine)"
OPT="-O2"
if [ "${RECONFIGURE:-0}" = 1 ]; then rm -rf wasm; fi
mkdir -p wasm && cd wasm
if [ ! -f config.status ] || [ "${RECONFIGURE:-0}" = 1 ]; then
  emconfigure ../src/configure "${COMMON_FLAGS[@]}" \
    --host=wasm32-unknown-emscripten --build="$BUILD_TRIPLE" \
    CFLAGS="$OPT" CXXFLAGS="$OPT" \
    BUILDCC=gcc BUILDCXX=g++ \
    OTANGLE=/usr/bin/true \
    > configure.log 2>&1 || { tail -40 configure.log; exit 1; }
fi
# Build libs + kpathsea + the web2c tree. Some web2c helpers we do not ship (ctwill-refsort, ...) do not
# link under emscripten, so keep going and then require only the two programs we need.
emmake make -k -j"$JOBS" > make.log 2>&1 || echo "(some unrelated targets failed; see make.log)"
emmake make -C texk/web2c pdftex bibtex > make-engines.log 2>&1 || { grep -n -i -B2 "error" make-engines.log | tail -40; exit 1; }

# Relink the two programs we ship as ES-module factories for Web Workers (and Node, for format builds).
EM_LINK=(
  -sMODULARIZE=1 -sEXPORT_ES6=1 -sINVOKE_RUN=0 -sEXIT_RUNTIME=0
  -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=134217728 -sMAXIMUM_MEMORY=2147483648
  -sSTACK_SIZE=8388608
  -sFORCE_FILESYSTEM=1
  -sENVIRONMENT=web,worker,node
  -sEXPORTED_RUNTIME_METHODS=callMain,FS,ENV
  -sWASM_BIGINT=1
)
cd texk/web2c
rm -f pdftex pdftex.wasm bibtex bibtex.wasm
emmake make pdftex LDFLAGS="${EM_LINK[*]} -sEXPORT_NAME=createPdftex" > link-pdftex.log 2>&1 || { tail -30 link-pdftex.log; exit 1; }
emmake make bibtex LDFLAGS="${EM_LINK[*]} -sEXPORT_NAME=createBibtex" > link-bibtex.log 2>&1 || { tail -30 link-bibtex.log; exit 1; }
cp pdftex /out/pdftex.mjs
cp pdftex.wasm /out/pdftex.wasm
cp bibtex /out/bibtex.mjs
cp bibtex.wasm /out/bibtex.wasm
mkdir -p /out/native-bin && cp "$B"/native-bin/* /out/native-bin/
{
  echo "texlive-source: ${TL_VER}"
  echo "emscripten: $(emcc --version | head -1)"
  echo "pdftex: $("$B/native-bin/pdftex" --version | head -1)"
  echo "bibtex: $("$B/native-bin/bibtex" --version | head -1)"
} > /out/versions.txt
cat /out/versions.txt
ls -la /out
