#!/usr/bin/env bash
# Re-compile app.jsx -> app.js so the browser can load it directly,
# without shipping ~3MB of @babel/standalone to every visitor.
#
# Usage: deploy/build.sh
# Run this before `git commit` whenever app.jsx changes.
set -euo pipefail

cd "$(dirname "$0")/.."
ROOT="$PWD"

# Use a dedicated build dir so we don't litter the repo root with
# node_modules / package-lock.json.
BUILD_DIR=".build"
mkdir -p "$BUILD_DIR"

if [ ! -f "$BUILD_DIR/package.json" ]; then
  # Write package.json directly — `npm init -y` rejects the leading-dot dir name.
  cat > "$BUILD_DIR/package.json" <<'EOF'
{ "name": "facere-build", "version": "1.0.0", "private": true }
EOF
fi
if [ ! -d "$BUILD_DIR/node_modules/@babel/preset-react" ]; then
  ( cd "$BUILD_DIR" && npm install --silent --no-audit --no-fund \
       @babel/core@7 @babel/cli@7 @babel/preset-react@7 )
fi

# Resolve the preset by absolute path: babel CLI runs from the repo root and
# wouldn't find it via the bare name (preset lives in .build/node_modules).
"$BUILD_DIR/node_modules/.bin/babel" app.jsx \
  --presets="$ROOT/$BUILD_DIR/node_modules/@babel/preset-react" \
  -o app.js

echo "Built app.js ($(wc -c < app.js) bytes)"
