#!/usr/bin/env bash
# FleetTruck360 — build the upload zips for the live cPanel server (see deploy/README.md).
#
#   deploy/build-release.sh api        → deploy/release/fleettruck360-api.zip      (Laravel, production vendor, no .env / tests)
#   deploy/build-release.sh app        → deploy/build/app/      + deploy/release/fleettruck360-app.zip      (app.fleettruck360.com)
#   deploy/build-release.sh website    → deploy/build/website/  + deploy/release/fleettruck360-website.zip  (public_html)
#
# deploy/build/ is COMMITTED: cPanel "Deploy HEAD Commit" (.cpanel.yml → deploy/cpanel-deploy.sh) copies these ready builds
# into place, because the server has no Node.js. Rebuild them before every push that changes the dashboard or website.
#   deploy/build-release.sh all
#
# The dashboard / website take their public settings from deploy/env/app.env and deploy/env/website.env.
# The website reads plans, blog posts and assistant answers from the LIVE API while building, so build it after the API
# is live. ALLOW_LOCAL_API=1 builds it from the API on this computer instead (local plans / posts — only for a first try).
# Nothing in backend/, frontend/ or website/ is changed, except website/dist (a build folder).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/deploy/release"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$OUT"
STAMP="$(date -u +%Y-%m-%dT%H:%MZ) · $(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || echo no-git) (+ uncommitted changes: $(git -C "$ROOT" status --porcelain 2>/dev/null | wc -l | tr -d ' '))"

# KEY=VALUE lines → exported variables (values may contain spaces and brackets; # lines are comments)
load_env() {
  while IFS= read -r line || [ -n "$line" ]; do
    [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
    key="${line%%=*}"; value="${line#*=}"
    value="${value%\"}"; value="${value#\"}"
    export "$key=$value"
  done < "$1"
}

build_api() {
  echo "── API ─────────────────────────────────────────────"
  rsync -a "$ROOT/backend/" "$TMP/api/" \
    --exclude '/.env' --exclude '/.env.*' --include '.env.example' \
    --exclude '/vendor/' --exclude '/node_modules/' --exclude '/tests/' --exclude '/storage/' \
    --exclude '/public/storage' --exclude '/public/hot' \
    --exclude '/bootstrap/cache/*.php' --exclude '/.phpunit.cache/' --exclude '.phpunit.result.cache' \
    --exclude '*.log' --exclude '/database/*.sqlite'
  cp "$ROOT/backend/.env.example" "$TMP/api/.env.example"
  # empty storage folders (only their .gitignore files): uploads, logs and caches stay on the server
  (cd "$ROOT" && git ls-files backend/storage backend/bootstrap/cache) | while read -r f; do
    mkdir -p "$TMP/api/$(dirname "${f#backend/}")"; cp "$ROOT/$f" "$TMP/api/${f#backend/}"
  done
  cp "$ROOT/deploy/env/api.env" "$TMP/api/.env.production.example"
  echo "$STAMP" > "$TMP/api/RELEASE.txt"
  (cd "$TMP/api" && composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist --quiet)
  rm -f "$OUT/fleettruck360-api.zip"
  (cd "$TMP" && zip -qr "$OUT/fleettruck360-api.zip" api)
  echo "✓ $(du -h "$OUT/fleettruck360-api.zip" | cut -f1)  deploy/release/fleettruck360-api.zip"
}

build_app() {
  echo "── Dashboard ───────────────────────────────────────"
  ( load_env "$ROOT/deploy/env/app.env"
    cd "$ROOT/frontend" && npx vite build --outDir "$TMP/app" --emptyOutDir --logLevel warn )
  cp "$ROOT/deploy/htaccess/app.htaccess" "$TMP/app/.htaccess"
  echo "$STAMP" > "$TMP/app/RELEASE.txt"
  grep -rq "localhost:8010" "$TMP/app/assets" && { echo "✗ the build still points at localhost — check deploy/env/app.env"; exit 1; }
  rm -rf "$ROOT/deploy/build/app" && mkdir -p "$ROOT/deploy/build" && cp -r "$TMP/app" "$ROOT/deploy/build/app"
  rm -f "$OUT/fleettruck360-app.zip"
  (cd "$TMP/app" && zip -qr "$OUT/fleettruck360-app.zip" .)
  echo "✓ deploy/build/app (goes live with the next push + cPanel Deploy)"
  echo "✓ $(du -h "$OUT/fleettruck360-app.zip" | cut -f1)  deploy/release/fleettruck360-app.zip"
}

build_website() {
  echo "── Website ─────────────────────────────────────────"
  ( load_env "$ROOT/deploy/env/website.env"
    if ! curl -sf -m 15 "$BUILD_API_URL/public/plans" > /dev/null; then
      if [ "${ALLOW_LOCAL_API:-}" = "1" ]; then
        echo "! $BUILD_API_URL does not answer — using the API on this computer (local plans / blog posts)"
        export BUILD_API_URL="http://localhost:8010/api/v1"
        curl -sf -m 15 "$BUILD_API_URL/public/plans" > /dev/null || { echo "✗ the local API is not running (scripts/dev.sh start)"; exit 1; }
      else
        echo "✗ $BUILD_API_URL does not answer. Put the API live first (deploy/README.md step 3),"
        echo "  or build from this computer's API for a first try: ALLOW_LOCAL_API=1 deploy/build-release.sh website"
        exit 1
      fi
    fi
    cd "$ROOT/website" && npx astro build --silent )
  cp -r "$ROOT/website/dist" "$TMP/website"
  cp "$ROOT/deploy/htaccess/website.htaccess" "$TMP/website/.htaccess"
  echo "$STAMP" > "$TMP/website/RELEASE.txt"
  grep -rlq "localhost:" "$TMP/website" --include=*.html && { echo "✗ the build still points at localhost — check deploy/env/website.env"; exit 1; }
  rm -rf "$ROOT/deploy/build/website" && mkdir -p "$ROOT/deploy/build" && cp -r "$TMP/website" "$ROOT/deploy/build/website"
  echo "✓ deploy/build/website (goes live with the next push + cPanel Deploy)"
  rm -f "$OUT/fleettruck360-website.zip"
  (cd "$TMP/website" && zip -qr "$OUT/fleettruck360-website.zip" .)
  echo "✓ $(du -h "$OUT/fleettruck360-website.zip" | cut -f1)  deploy/release/fleettruck360-website.zip"
}

case "${1:-}" in
  api) build_api ;;
  app) build_app ;;
  website) build_website ;;
  all) build_api; build_app; build_website ;;
  *) echo "usage: deploy/build-release.sh api|app|website|all"; exit 1 ;;
esac
