#!/usr/bin/env bash
#
# Roll out a new version that is already in place in APP_DIR:
#   sudo bash scripts/deploy.sh
#
# Order matters: back up → migrate → clear opcode cache → restart workers, so no worker
# keeps running old code against a new schema.

set -euo pipefail

APP_DIR="${APP_DIR:-/var/www/gostardeh}"
APP_USER="${APP_USER:-gostardeh}"
PHP_BIN="${PHP_BIN:-/usr/bin/php}"
PHP_FPM_SERVICE="${PHP_FPM_SERVICE:-php8.3-fpm}"

run() { sudo -u "$APP_USER" "$PHP_BIN" "$APP_DIR/bin/console" "$@"; }

echo "==> Backup before migrating"
run backup:run

echo "==> Migrations"
run migrate
run db:seed

echo "==> Reload PHP-FPM (opcache) and restart workers"
systemctl reload "$PHP_FPM_SERVICE"
supervisorctl restart 'gostardeh:*'

echo "==> Health"
sleep 5
run health:check || { echo "Health check reported a failure — inspect storage/logs/errors-*.log" >&2; exit 1; }
echo "Deployed."
