#!/usr/bin/env bash
# Rebuild piper_phonemize.{js,wasm,data} as shipped in @diffusionstudio/piper-wasm@1.0.0
# (eSpeak NG + piper-phonemize compiled to WebAssembly with Emscripten 3.1.47).
#
# SOURCE OF THESE STEPS
#   The commands are the build instructions published in the package README
#   (https://cdn.jsdelivr.net/npm/@diffusionstudio/piper-wasm@1.0.0/README.md, "As of JUN 2024"),
#   which repeat https://github.com/wide-video/piper-wasm (README, "Build WASM").
#   The sed commands below are copied verbatim from that README.
#
# OUR RECONSTRUCTION (chessGM), marked "[chessGM]" below:
#   - Upstream cloned branch heads with `git clone --depth 1` and no pinned commit. We pin the
#     commits those heads pointed to when the package was built (June/July 2024) and download
#     GitHub archive tarballs instead of cloning:
#       rhasspy/espeak-ng          8593723f10cfd9befd50de447f14bf0a9d2a14a4  (master; repo archived
#                                  2023-11-29, so this head cannot have moved)
#       wide-video/piper-phonemize cfff8e52ebaea37c7e953ae2d06b174acb827ac4  (default branch
#                                  "wide.video"; last push 2024-04-02, before the build)
#     piper-phonemize's own CMakeLists.txt downloads the eSpeak NG code that is compiled into the
#     wasm from a URL pinned to rhasspy/espeak-ng commit 0f65aa301e0d6bae5e172cc74197d32a6182200f;
#     we leave that as is (and pre-fetch it, with a checksum, so the build is checkable).
#   - emsdk itself is pinned to its 3.1.47 tag; upstream cloned emsdk HEAD and then ran
#     `emsdk install 3.1.47`, which installs the same Emscripten 3.1.47 SDK.
#   - The speechWaveGenerator.cpp sed is equivalent to build.patch (shipped next to this file).
#   - SHA-256 checks of the downloads. We have not verified that this produces byte-identical
#     output (Emscripten builds are not guaranteed bit-for-bit reproducible); the expected hashes
#     of the published files are printed at the end for comparison.
#
# Run inside a Debian 11.3 container, as upstream did:
#   docker run -it -v "$(pwd)":/wasm -w /wasm debian:11.3 bash /wasm/build.sh
set -euo pipefail

W=/wasm/modules
mkdir -p "$W"

apt-get update
apt-get install --yes --no-install-recommends build-essential cmake ca-certificates curl pkg-config git python3 autogen automake autoconf libtool

fetch() { # url file sha256   [chessGM]
	curl -fsSL -o "$2" "$1"
	echo "$3  $2" | sha256sum -c -
}

# ---------- Emscripten 3.1.47 ----------
# [chessGM] emsdk pinned to tag 3.1.47 (commit 37b85e9eaee5be090569d018cca77a15cacc11b7).
git clone https://github.com/emscripten-core/emsdk.git "$W/emsdk"
git -C "$W/emsdk" checkout 37b85e9eaee5be090569d018cca77a15cacc11b7
cd "$W/emsdk"
./emsdk install 3.1.47
./emsdk activate 3.1.47
# shellcheck disable=SC1091
source ./emsdk_env.sh
TOOLCHAIN_FILE=$EMSDK/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake
# Verbatim from upstream: comment out the isw*() prototypes in the toolchain's wchar.h.
sed -i -E 's/int\s+(iswalnum|iswalpha|iswblank|iswcntrl|iswgraph|iswlower|iswprint|iswpunct|iswspace|iswupper|iswxdigit)\(wint_t\)/\/\/\0/g' ./upstream/emscripten/cache/sysroot/include/wchar.h

# ---------- espeak-ng (native build; compiles the voice data that goes into piper_phonemize.data) ----------
# Upstream: git clone --depth 1 https://github.com/rhasspy/espeak-ng.git /wasm/modules/espeak-ng
# [chessGM] pinned to the archived master head.
cd "$W"
fetch https://github.com/rhasspy/espeak-ng/archive/8593723f10cfd9befd50de447f14bf0a9d2a14a4.tar.gz \
	espeak-ng-8593723.tar.gz 41c199da1355deec93eab6065be99d00b938dd452e78f282ab481db91657e4e4
mkdir -p "$W/espeak-ng"
tar -xzf espeak-ng-8593723.tar.gz -C "$W/espeak-ng" --strip-components=1
cd "$W/espeak-ng"
./autogen.sh
./configure
make

# ---------- piper-phonemize (wasm build; statically links eSpeak NG 0f65aa3) ----------
# Upstream: git clone --depth 1 https://github.com/wide-video/piper-phonemize.git /wasm/modules/piper-phonemize
# [chessGM] pinned to the wide.video branch head.
cd "$W"
fetch https://github.com/wide-video/piper-phonemize/archive/cfff8e52ebaea37c7e953ae2d06b174acb827ac4.tar.gz \
	piper-phonemize-cfff8e5.tar.gz 7029b52aabc2512d36f4d98c6ede732c48a0e7128d0cd0e62379dfcee770038e
mkdir -p "$W/piper-phonemize"
tar -xzf piper-phonemize-cfff8e5.tar.gz -C "$W/piper-phonemize" --strip-components=1

# [chessGM] Pre-fetch and check the eSpeak NG archive that CMakeLists.txt downloads
# (URL "https://github.com/rhasspy/espeak-ng/archive/0f65aa301e0d6bae5e172cc74197d32a6182200f.zip").
# GitHub generates archives on the fly; if this checksum ever stops matching, compare the
# extracted tree with the .tar.gz listed in SOURCE.txt instead.
fetch https://github.com/rhasspy/espeak-ng/archive/0f65aa301e0d6bae5e172cc74197d32a6182200f.zip \
	"$W/espeak-ng-0f65aa3.zip" 150fc955926a084a77ebe25c9e8287bde2e2a17bbf9b23a25c147b556837949f

cd "$W/piper-phonemize"
emmake cmake -Bbuild -DCMAKE_INSTALL_PREFIX=install -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_FILE -DBUILD_TESTING=OFF -G "Unix Makefiles" -DCMAKE_CXX_FLAGS="-O3 -s INVOKE_RUN=0 -s MODULARIZE=1 -s EXPORT_NAME='createPiperPhonemize' -s EXPORTED_FUNCTIONS='[_main]' -s EXPORTED_RUNTIME_METHODS='[callMain, FS]' --preload-file /wasm/modules/espeak-ng/espeak-ng-data@/espeak-ng-data"
# Upstream note: fails on "Compile intonations / Permission denied", continue with next steps.
emmake cmake --build build --config Release || true
# Verbatim from upstream: skip eSpeak NG's own data target in the wasm sub-build.
sed -i 's+$(MAKE) $(MAKESILENT) -f CMakeFiles/data.dir/build.make CMakeFiles/data.dir/build+#\0+g' /wasm/modules/piper-phonemize/build/e/src/espeak_ng_external-build/CMakeFiles/Makefile2
# Verbatim from upstream (same change as build.patch):
sed -i 's/using namespace std/\/\/\0/g' /wasm/modules/piper-phonemize/build/e/src/espeak_ng_external/src/speechPlayer/src/speechWaveGenerator.cpp
emmake cmake --build build --config Release

# Output: /wasm/modules/piper-phonemize/build/piper_phonemize.{js,wasm,data}
cd "$W/piper-phonemize/build"
ls -l piper_phonemize.js piper_phonemize.wasm piper_phonemize.data
sha256sum piper_phonemize.js piper_phonemize.wasm piper_phonemize.data
echo "Published @diffusionstudio/piper-wasm@1.0.0 files, for comparison:"
echo "fef0c2fc442d24fdef5c7c7cc37d5da2314407640fe11ab1bfe347c723dff19b  piper_phonemize.js"
echo "b777cd107a91d2bcc6a1ea46f2c26a662a7407394fe84589198aeaa83dd7a9d6  piper_phonemize.wasm"
echo "29f1025eb23a5b5c192cd14a6efbce4509402ff265405072ee6f7d1a09b78f8c  piper_phonemize.data"
