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

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$HERE/editor-src"
OUT="$HERE/../l4d2web/static/vendor"

cd "$SRC"

# Honor an existing $NPM_CACHE override; fall back to $TMPDIR if the
# default ~/.npm cache is unwritable (root-owned files from older npm
# versions are a common cause; see ~/.npm/_logs).
NPM_CACHE="${NPM_CACHE:-$TMPDIR/npm-cache}"
npm install --cache "$NPM_CACHE"

# Build all bundles via npm run build (editor.bundle.js + vocab-rank.bundle.js).
# Do not call npx esbuild directly — package.json is the single source of truth
# for build targets so new bundles are never silently omitted.
npm run build

# cm6 injects its styles at runtime via the StyleModule machinery, so the
# bundle does not produce a separate .css file. We create an empty
# editor.bundle.css so the partial template's <link> tag points at
# something concrete (and future extensions that produce real CSS can
# drop it in without a template change).
: > "$OUT/editor.bundle.css"

(cd "$OUT" && shasum -a 256 editor.bundle.js editor.bundle.css vocab-rank.bundle.js > editor.bundle.sha256)

echo "Built $OUT/editor.bundle.js ($(wc -c < "$OUT/editor.bundle.js") bytes)"
echo "Built $OUT/vocab-rank.bundle.js ($(wc -c < "$OUT/vocab-rank.bundle.js") bytes)"
