#!/usr/bin/env bash
# Build a cPanel-ready ZIP: production Composer deps + Vite assets. No server-side Composer/NPM required.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

echo "==> composer install (no dev, optimized autoloader)"
composer install --no-dev --optimize-autoloader --no-interaction

echo "==> npm ci && npm run build (legacy-peer-deps: vite-plugin-pwa vs Vite 8)"
npm ci --legacy-peer-deps
npm run build

if [[ ! -f vendor/autoload.php ]]; then
  echo "ERROR: vendor/autoload.php missing after composer install." >&2
  exit 1
fi
if [[ ! -f public/build/manifest.json ]]; then
  echo "ERROR: public/build/manifest.json missing after npm run build." >&2
  exit 1
fi

STAGE="$(mktemp -d)"
cleanup() { rm -rf "$STAGE"; }
trap cleanup EXIT

NAME="collabs"
DEST="$STAGE/$NAME"
mkdir -p "$DEST"

echo "==> staging (excluding git, node_modules, tests, local env, caches)"
rsync -a \
  --delete \
  --exclude='.git' \
  --exclude='node_modules' \
  --exclude='tests' \
  --exclude='dist' \
  --exclude='.env' \
  --exclude='.env.*' \
  --exclude='.phpunit.result.cache' \
  --exclude='storage/app/.installed' \
  --exclude='public/hot' \
  --exclude='public/storage' \
  "$ROOT/" "$DEST/"

echo "==> clearing volatile storage paths in staging"
rm -rf "${DEST}/storage/logs/"*
rm -rf "${DEST}/storage/framework/cache/data/"*
rm -rf "${DEST}/storage/framework/sessions/"*
rm -rf "${DEST}/storage/framework/views/"*
mkdir -p "${DEST}/storage/logs" \
  "${DEST}/storage/framework/cache/data" \
  "${DEST}/storage/framework/sessions" \
  "${DEST}/storage/framework/views"
touch "${DEST}/storage/logs/.gitkeep" 2>/dev/null || true

mkdir -p "$ROOT/dist"
ZIP="$ROOT/dist/${NAME}-cpanel-$(date +%Y%m%d-%H%M%S).zip"
( cd "$STAGE" && zip -r -q "$ZIP" "$NAME" )

echo "==> done: $ZIP"
ls -lh "$ZIP"
