#!/usr/bin/env bash
#
# Builds public/vendor/liblouis/ — liblouis compiled to WebAssembly, with the
# Unified English Braille tables embedded — for /en/braille-translator/.
#
# liblouis is LGPL-2.1-or-later. The LGPL lets us use it from our own code as
# long as the library stays a separate, replaceable file and anyone can get its
# source and rebuild it. This script is the "rebuild it" half: it starts from
# the unmodified upstream release tarball, checked by hash, and produces the
# exact two files we ship. Nothing in liblouis is patched.
#
# The LGPL also asks that the source and the way to rebuild it come from the
# same place as the binary. So the script leaves in that folder, next to the two
# files, the release tarball it built from, a copy of itself and the licences.
# The repository is private; braillito.com/vendor/liblouis/ is the public place.
#
# Requires emsdk (https://emscripten.org). emsdk itself needs Python 3.10+:
#
#   git clone https://github.com/emscripten-core/emsdk.git
#   EMSDK_PYTHON=python3.12 ./emsdk/emsdk install latest && ./emsdk/emsdk activate latest
#   EMSDK=$PWD/emsdk EMSDK_PYTHON=python3.12 scripts/build-liblouis-wasm.sh
#
# Outside this repository, from the copy published with the library:
#
#   OUT=./out TARBALL=./liblouis-3.39.0.tar.gz EMSDK=... ./build-liblouis-wasm.sh
#
# Built and verified with emcc 6.0.10 on 2026-09-28.

set -euo pipefail

VERSION=3.39.0
SHA256=629fa8cb0dfd9ad457c5bf47a42f0953b673e62c8ad6b1d03ddc4e2bd20008f1
URL="https://github.com/liblouis/liblouis/releases/download/v${VERSION}/liblouis-${VERSION}.tar.gz"

SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="${OUT:-$ROOT/public/vendor/liblouis}"
OUT="$(mkdir -p "$OUT" && cd "$OUT" && pwd)"
: "${EMSDK:?Set EMSDK to your emsdk checkout}"

# shellcheck disable=SC1091
source "$EMSDK/emsdk_env.sh" >/dev/null 2>&1

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
cd "$WORK"

if [ -n "${TARBALL:-}" ]; then
    cp "$TARBALL" liblouis.tar.gz
else
    curl -sSfL -o liblouis.tar.gz "$URL"
fi
echo "$SHA256  liblouis.tar.gz" | shasum -a 256 -c -
tar xzf liblouis.tar.gz
SRC="$WORK/liblouis-$VERSION"

# Only for config.h. The autotools build itself is not used: on macOS it
# injects -arch flags that do not exist for wasm32.
(cd "$SRC" && emconfigure ./configure --disable-shared --without-yaml >/dev/null)

# The tables the page asks for, plus everything they include, recursively.
mkdir tables
python3 - "$SRC/tables" tables <<'PY'
import re, shutil, sys, pathlib
src, dst = map(pathlib.Path, sys.argv[1:])
seen, todo = set(), ["en-ueb-g1.ctb", "en-ueb-g2.ctb", "unicode.dis"]
while todo:
    name = todo.pop()
    if name in seen:
        continue
    seen.add(name)
    for line in (src / name).read_text(encoding="utf-8").splitlines():
        m = re.match(r"\s*include\s+(\S+)", line)
        if m:
            todo.append(m.group(1))
for name in sorted(seen):
    shutil.copy(src / name, dst / name)
print("tables:", " ".join(sorted(seen)))
PY

# Not -I gnulib: its replacement headers rename malloc/free to rpl_* symbols
# that only exist in gnulib's own build.
emcc -O3 -DHAVE_CONFIG_H -I"$SRC/liblouis" -DTABLESDIR='"/tables"' \
    "$SRC"/liblouis/{commonTranslationFunctions,compileTranslationTable,logging,lou_backTranslateString,lou_translateString,maketable,metadata,pattern,utils}.c \
    -o liblouis.js \
    -sMODULARIZE=1 -sEXPORT_ES6=1 -sEXPORT_NAME=createLiblouis -sENVIRONMENT=web,node \
    -sALLOW_MEMORY_GROWTH=1 -sFILESYSTEM=1 \
    -sEXPORTED_FUNCTIONS=_lou_translateString,_lou_backTranslateString,_lou_version,_lou_setLogLevel,_malloc,_free \
    -sEXPORTED_RUNTIME_METHODS=UTF8ToString,stringToNewUTF8,HEAPU16,HEAP32 \
    --embed-file tables@/tables \
    -Wno-ignored-attributes

cp liblouis.js liblouis.wasm "$OUT/"
cp "$SRC/COPYING.LESSER" "$OUT/COPYING.LESSER"
# Corresponding source, and the script that turns it into the two files above.
cp liblouis.tar.gz "$OUT/liblouis-$VERSION.tar.gz"
[ "$SELF" -ef "$OUT/build-liblouis-wasm.sh" ] || cp "$SELF" "$OUT/build-liblouis-wasm.sh"
# THIRD-PARTY-NOTICES.txt (Emscripten and musl licences) is kept by hand: if you
# change the emcc version, replace the two texts in it with that release's.
echo "✅ $OUT: liblouis $VERSION ($(wc -c < liblouis.wasm | tr -d ' ') bytes of wasm)"
