#!/usr/bin/env bash
# Build a Linux-ready cPanel bundle on this Mac (via Docker), so the server only needs extract + Restart.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
STAGE="$ROOT/.cpanel-stage"
OUT="${1:-$ROOT/../community-cpanel-built.zip}"
IMAGE="${CPANEL_NODE_IMAGE:-node:20-bookworm}"

cd "$ROOT"

if ! command -v docker >/dev/null 2>&1; then
  echo "Docker is required so we can build Linux binaries (cPanel is Linux, this Mac is not)." >&2
  exit 1
fi

if [[ ! -f prisma/dev.db ]]; then
  echo "Missing prisma/dev.db — run: npm run db:seed" >&2
  exit 1
fi

rm -rf "$STAGE" 2>/dev/null || true
if [[ -d "$STAGE" ]]; then
  # Docker may leave root-owned files
  docker run --rm -v "$ROOT:/app" alpine rm -rf /app/.cpanel-stage
fi
mkdir -p "$STAGE"

echo "==> Copying source into staging…"
rsync -a \
  --exclude node_modules \
  --exclude .next \
  --exclude .cpanel-stage \
  --exclude '.git' \
  --exclude '*.tsbuildinfo' \
  --exclude .env \
  --exclude '.DS_Store' \
  "$ROOT/" "$STAGE/"

# Production env baked for the domain (override on server if needed)
cat > "$STAGE/.env" <<'EOF'
DATABASE_URL="file:./dev.db"
AUTH_SECRET="elbeegems-community-preview-change-me"
NEXT_PUBLIC_APP_URL="https://community.elbeegems.com"
NODE_ENV="production"
USE_DEMO_DATA="1"
EOF

if [[ ! -f data/demo.json ]]; then
  echo "Missing data/demo.json — run: npx tsx scripts/export-demo.ts" >&2
  exit 1
fi

echo "==> Building inside Docker (linux/amd64) — this takes a few minutes…"
docker run --rm --platform linux/amd64 \
  -v "$STAGE:/app" \
  -w /app \
  -e DATABASE_URL="file:./dev.db" \
  -e NEXT_TELEMETRY_DISABLED=1 \
  "$IMAGE" \
  bash -lc 'set -euo pipefail; npm ci; npx prisma generate; npm run build; npm prune --omit=dev'

# Ensure runtime pieces exist
test -d "$STAGE/.next"
test -d "$STAGE/node_modules"
test -f "$STAGE/server.js"
test -f "$STAGE/prisma/dev.db"
test -f "$STAGE/data/demo.json"

echo "==> Zipping…"
rm -f "$OUT"
(
  cd "$STAGE"
  zip -r "$OUT" . \
    -x "*.tsbuildinfo" \
    -x ".DS_Store" \
    -x "*/.DS_Store"
)

echo ""
echo "Wrote: $OUT"
echo "Size:  $(du -h "$OUT" | awk '{print $1}')"
echo ""
echo "Upload & extract into your cPanel Node app root, then:"
echo "  1. Startup file = server.js"
echo "  2. Click Restart"
echo "  3. No npm build needed on the server"
echo ""
echo "Staging kept at: $STAGE (delete when done)"
