#!/usr/bin/env bash
# Convert TTF files to woff/woff2 using the Rust `woff` crate CLI
# Usage: ttf2web.sh <input_dir> [output_dir]
# Requires: cargo install woff

set -euo pipefail

SRCDIR="${1:?Usage: ttf2web.sh <input_dir> [output_dir]}"
OUTDIR="${2:-webfonts}"

if ! command -v woff &>/dev/null; then
  echo "Error: 'woff' CLI not found. Install with: cargo install woff"
  exit 1
fi

mkdir -p "$OUTDIR"

declare -A families_seen

for ttf in "$SRCDIR"/*.ttf "$SRCDIR"/*.TTF; do
  [ -f "$ttf" ] || continue

  base="$(basename "$ttf" .ttf)"
  base="$(basename "$base" .TTF)"

  echo "Converting: $base"
  woff "$ttf" "$OUTDIR/${base}.woff"
  woff "$ttf" "$OUTDIR/${base}.woff2"

  weight_name="${base##*-}"
  family="${base%-*}"

  if [ "$weight_name" = "$base" ]; then
    weight_name="Regular"
    family="$base"
  fi

  case "$weight_name" in
    Thin|Hairline)          weight=100 ;;
    ExtraLight|UltraLight)  weight=200 ;;
    Light)                  weight=300 ;;
    Regular|Normal|Book)    weight=400 ;;
    Medium)                 weight=500 ;;
    SemiBold|DemiBold)      weight=600 ;;
    Bold)                   weight=700 ;;
    ExtraBold|UltraBold)    weight=800 ;;
    Black|Heavy)            weight=900 ;;
    *)                      weight=400 ;;
  esac

  style="normal"
  if [[ "$weight_name" == *Italic* ]] || [[ "$base" == *Italic* ]]; then
    style="italic"
  fi

  css_file="$OUTDIR/${family}.css"
  if [ -z "${families_seen[$family]:-}" ]; then
    > "$css_file"
    families_seen[$family]=1
  fi

  src_parts=()
  [ -f "$OUTDIR/${base}.woff2" ] && src_parts+=("url('${base}.woff2') format('woff2')")
  [ -f "$OUTDIR/${base}.woff" ]  && src_parts+=("url('${base}.woff') format('woff')")

  [ ${#src_parts[@]} -eq 0 ] && continue

  src_value="$(printf '%s,\n       ' "${src_parts[@]}")"
  src_value="${src_value%,*}"

  cat >> "$css_file" <<EOF
@font-face {
  font-family: '${family}';
  font-style: ${style};
  font-weight: ${weight};
  font-display: swap;
  src: ${src_value};
}

EOF

done

echo ""
echo "Output: $OUTDIR/"
for css in "$OUTDIR"/*.css; do
  [ -f "$css" ] || continue
  faces=$(grep -c '@font-face' "$css")
  echo "  $(basename "$css") (${faces} faces)"
done
