#!/usr/bin/env bash
# Run on the server after uploading and extracting a release:
#   cd ~/central-api && bash deploy/postdeploy.sh
# Safe to re-run. Set PHP_BIN if the cPanel CLI php is not the web PHP version,
# e.g. PHP_BIN=/opt/cpanel/ea-php83/root/usr/bin/php bash deploy/postdeploy.sh
set -euo pipefail
cd "$(dirname "$0")/.."
PHP="${PHP_BIN:-php}"

"$PHP" deploy/preflight.php

if ! grep -qE '^APP_KEY=base64:.+' .env; then
  echo "Generating APP_KEY"
  "$PHP" artisan key:generate --force
fi

"$PHP" artisan down --retry=15 >/dev/null 2>&1 || true
trap '"$PHP" artisan up >/dev/null 2>&1 || true' EXIT

"$PHP" artisan migrate --force
# Creates any site from config/central.php that does not exist yet and prints
# its keys ONCE. Copy them from this output.
"$PHP" artisan central:install --no-interaction
"$PHP" artisan optimize:clear >/dev/null
"$PHP" artisan optimize
"$PHP" artisan filament:optimize
"$PHP" artisan queue:restart >/dev/null

echo "Deploy complete: $(cat BUILD_INFO 2>/dev/null || echo 'unknown build')"
