#!/usr/bin/env bash
# Vendor the landing-page web fonts locally so the apex site works on an
# offline LAN (no Google Fonts CDN at party time).
#
# Pulls woff2 + a rewritten @font-face stylesheet from Google Fonts into
# landing/public/fonts/. Re-run only when the font set changes.
#
# Halts on any error (cautious-by-default).
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
out="$here/landing/public/fonts"
mkdir -p "$out"

# Modern Chrome UA → Google returns woff2 (not ttf).
UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"

# Families + weights used by the landing (keep in sync with main.css --font-*).
CSS_URL="https://fonts.googleapis.com/css2"
CSS_URL+="?family=Pixelify+Sans:wght@600;700"
CSS_URL+="&family=Space+Grotesk:wght@400;500;600;700"
CSS_URL+="&family=Press+Start+2P"
CSS_URL+="&family=Silkscreen:wght@400;700"
CSS_URL+="&family=VT323"
CSS_URL+="&display=swap"

echo "→ fetching @font-face CSS"
raw="$(curl -fsSL -A "$UA" "$CSS_URL")"

echo "→ downloading woff2 files"
# Pull every gstatic woff2 URL, download to out/, dedupe by basename.
echo "$raw" | grep -oE 'https://fonts\.gstatic\.com/[^)]+\.woff2' | sort -u | while read -r url; do
  fn="$(basename "$url")"
  if [ ! -f "$out/$fn" ]; then
    curl -fsSL -o "$out/$fn" "$url"
    echo "   $fn"
  fi
done

echo "→ writing fonts.css (URLs rewritten to /fonts/…)"
# Rewrite absolute gstatic URLs to local /fonts/<basename>.
echo "$raw" | sed -E 's#https://fonts\.gstatic\.com/[^)]+/([^)/]+\.woff2)#/fonts/\1#g' > "$out/fonts.css"

echo "✓ fonts vendored into $out"
