#!/usr/bin/env bash
# Builds an upload-ready zip for cPanel: production Composer dependencies,
# built CSS/JS, empty storage folders — no .env, tests, node_modules or local data.
#
#   ./scripts/package-release.sh            → dist/beauthentic-YYYYMMDD-HHMM.zip
#
# Upload the zip in cPanel File Manager, extract it, open https://your-domain/install.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
STAMP="$(date +%Y%m%d-%H%M)"
BUILD="$(mktemp -d)/beauthentic"
OUT="$ROOT/dist/beauthentic-$STAMP.zip"

echo "→ Building assets"
(cd "$ROOT" && npm ci --silent && npm run build --silent)

echo "→ Copying application"
mkdir -p "$BUILD"
rsync -a "$ROOT/" "$BUILD/" \
  --exclude '.git' --exclude 'node_modules' --exclude 'vendor' --exclude 'tests' --exclude 'dist' \
  --exclude '.env' --exclude '.env.backup' --exclude '.env.*.local' --exclude '.claude' --exclude '.idea' --exclude '.vscode' \
  --exclude 'storage' --exclude 'bootstrap/cache/*.php' --exclude 'public/storage' --exclude 'public/hot' \
  --exclude 'database/*.sqlite' --exclude 'design' --exclude '.phpunit.result.cache' --exclude '.DS_Store'

# Empty storage tree with the .gitignore placeholders Laravel expects.
(cd "$ROOT" && find storage -type d \( -path 'storage/app/backups*' -o -path 'storage/app/installer*' -o -path 'storage/framework/testing*' \) -prune -o -type d -print) | while read -r d; do
  case "$d" in storage/app/private/media/*|storage/app/public/*) continue;; esac
  mkdir -p "$BUILD/$d"
done
(cd "$ROOT" && find storage -name .gitignore -not -path '*/testing/*') | while read -r f; do cp "$ROOT/$f" "$BUILD/$f"; done
rm -f "$BUILD/storage/app/installed.lock"

echo "→ Installing production dependencies"
(cd "$BUILD" && composer install --no-dev --optimize-autoloader --no-interaction --quiet)

echo "→ Zipping"
mkdir -p "$ROOT/dist"
(cd "$BUILD" && zip -qr "$OUT" . -x '*.DS_Store')
rm -rf "$(dirname "$BUILD")"

echo "✓ $OUT ($(du -h "$OUT" | cut -f1))"
