#!/bin/bash
# Deploy this site to Cloudflare Pages
# Run: bash deploy.sh
#
# BEFORE FIRST DEPLOY: fill in the three REPLACE_WITH values below (see SETUP - fill these in.md).
# NOTE: this script intentionally writes NO wrangler.toml — env vars / D1 bindings
# live at the Pages PROJECT level and persist across deploys.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SITE_DIR="$SCRIPT_DIR/index"
PROJECT_NAME="REPLACE_WITH_PAGES_PROJECT_NAME"
ACCOUNT_ID="REPLACE_WITH_CLOUDFLARE_ACCOUNT_ID"
API_TOKEN="REPLACE_WITH_CLOUDFLARE_API_TOKEN"

for v in "$PROJECT_NAME" "$ACCOUNT_ID" "$API_TOKEN"; do
  case "$v" in REPLACE_WITH_*)
    echo "ERROR: fill in PROJECT_NAME / ACCOUNT_ID / API_TOKEN in deploy.sh first (see SETUP - fill these in.md)." >&2
    exit 1;;
  esac
done

if grep -rq "\[\[" "$SITE_DIR" --include="*.html"; then
  echo "WARNING: unreplaced [[TOKENS]] still exist in index/ — run the SETUP - fill these in.md find-and-replace first:" >&2
  grep -rho "\[\[[A-Z_]*\]\]" "$SITE_DIR" --include="*.html" | sort | uniq -c >&2
  echo "Deploy aborted." >&2
  exit 1
fi

# Every image the pages reference must exist (logo, headshot or company photo
# per brand mode, hero background) — a missing file would go live broken.
MISSING=""
while IFS= read -r img; do
  [ -f "$SITE_DIR/images/$img" ] || MISSING="$MISSING $img"
done < <(grep -rhoE "images/[A-Za-z0-9._-]+\.(png|jpe?g|svg|webp)" "$SITE_DIR" --include="*.html" | sed 's|.*images/||' | sort -u)
if [ -n "$MISSING" ]; then
  echo "ERROR: the site references these files but they are missing from index/images/:" >&2
  for f in $MISSING; do echo "  - $f" >&2; done
  echo "Add them (see SETUP - fill these in.md, section 5), then deploy again." >&2
  exit 1
fi

echo "Deploying $PROJECT_NAME from: $SITE_DIR"
cd "$SCRIPT_DIR"
CLOUDFLARE_API_TOKEN="$API_TOKEN" \
CLOUDFLARE_ACCOUNT_ID="$ACCOUNT_ID" \
wrangler pages deploy "$SITE_DIR" \
  --project-name="$PROJECT_NAME" \
  --commit-dirty=true

echo "✅ Deploy complete. Open the site and hard-refresh to confirm the change is live."
