#!/usr/bin/env bash
#
# Almasa CMS — production deployment / update (Ubuntu, see docs/DEPLOYMENT.md).
# Run as the deploy user from the application directory:   ./deploy.sh
#
# Safe to re-run. Takes a database backup before migrating; migrations are
# additive/reversible by project rule (zero data loss). Stops at the first error.

set -euo pipefail

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHP="${PHP:-php}"
BRANCH="${BRANCH:-main}"
cd "$APP_DIR"

step() { printf '\n\033[1;33m==> %s\033[0m\n' "$1"; }

[ -f .env ] || { echo "Missing .env — copy .env.example and fill it first (docs/DEPLOYMENT.md §5)."; exit 1; }
grep -q '^APP_ENV=production' .env || { echo "APP_ENV must be production in .env"; exit 1; }
grep -q '^APP_DEBUG=false' .env || { echo "APP_DEBUG must be false in .env"; exit 1; }

step "Maintenance mode on"
$PHP artisan down --retry=60 --refresh=15 || true
trap '$PHP artisan up >/dev/null 2>&1 || true' EXIT

if [ -d .git ]; then
  step "Pulling ${BRANCH}"
  git fetch --quiet origin "$BRANCH"
  git checkout --quiet "$BRANCH"
  git pull --ff-only --quiet origin "$BRANCH"
fi

step "PHP dependencies (no dev)"
composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader

step "Front-end build (Al Masa theme)"
npm ci --no-audit --no-fund
npm run build

step "Database backup before migrating"
$PHP artisan backup:run --only-db --disable-notifications

step "Migrations and permissions"
$PHP artisan migrate --force
$PHP artisan permissions:sync

step "Caches"
$PHP artisan optimize:clear
$PHP artisan optimize
$PHP artisan filament:optimize
$PHP artisan storage:link >/dev/null 2>&1 || true

step "Restart queue workers and PHP-FPM (reload OPcache)"
$PHP artisan queue:restart
if command -v sudo >/dev/null && sudo -n true 2>/dev/null; then
  sudo systemctl reload "php8.5-fpm" || true
else
  echo "  (no passwordless sudo: run 'sudo systemctl reload php8.5-fpm' yourself)"
fi

step "Maintenance mode off"
$PHP artisan up
trap - EXIT

step "Done. Check System → System health in the browser."
