#!/usr/bin/env bash
# Builds release/firstsittings-<date>-<commit>.zip: everything the cPanel server needs,
# ready to upload in File Manager and extract (no Terminal, Composer or Node needed there).
#
#   bash scripts/build-release.sh
#
# Uses the last *committed* code (git archive HEAD), so commit first.
set -euo pipefail

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

if [ -n "$(git status --porcelain)" ]; then
  echo "⚠  You have uncommitted changes. The release uses the last commit only."
fi

COMPOSER_PHAR="${COMPOSER_PHAR:-$HOME/.config/herd-lite/bin/composer.phar}"
composer_run() {
  if [ -f "$COMPOSER_PHAR" ]; then php "$COMPOSER_PHAR" "$@"; else composer "$@"; fi
}

VERSION="$(date +%Y%m%d-%H%M)-$(git rev-parse --short HEAD)"
OUT="$ROOT/release"
APP="$OUT/firstsittings"
ZIP="$OUT/firstsittings-$VERSION.zip"

echo "→ Exporting commit $(git rev-parse --short HEAD)"
rm -rf "$APP"
mkdir -p "$APP"
git archive HEAD | tar -x -C "$APP"

echo "→ Building CSS/JS"
npm run build --silent
cp -r public/build "$APP/public/build"

echo "→ Installing PHP packages (production only; also publishes Filament's assets)"
(cd "$APP" && composer_run install --no-dev --optimize-autoloader --no-interaction --no-progress --quiet)

echo "→ Removing files the server doesn't need"
(cd "$APP" && rm -rf tests .github docs/superpowers phpunit.xml .editorconfig vite.config.js package.json package-lock.json \
  bootstrap/cache/config.php bootstrap/cache/routes-*.php database/database.sqlite .env)

echo "→ Zipping"
rm -f "$ZIP"
php "$ROOT/scripts/zip-dir.php" "$APP" "$ZIP"

echo "→ Checking the zip opens as a real zip"
php -r '$z = new ZipArchive; $r = $z->open($argv[1], ZipArchive::CHECKCONS);
  if ($r !== true) { fwrite(STDERR, "✘ zip is broken (code $r)\n"); exit(1); }
  foreach (["firstsittings/artisan", "firstsittings/public/index.php", "firstsittings/vendor/autoload.php", "firstsittings/public/build/manifest.json"] as $f)
    if ($z->locateName($f) === false) { fwrite(STDERR, "✘ missing $f\n"); exit(1); }
  echo "  ok: ".$z->numFiles." entries\n";' "$ZIP"
rm -rf "$APP"

echo "✔ $ZIP ($(du -h "$ZIP" | cut -f1))"
