#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

TAG="${1:-latest}"
export LESSTIME_IMAGE_TAG="$TAG"

echo "==> Deploying lesstime:${TAG}..."

echo "==> Enabling maintenance mode..."
touch maintenance.on

echo "==> Pulling image..."
sudo docker compose pull

echo "==> Starting container..."
sudo docker compose up -d

echo "==> Waiting for container to be ready..."
sleep 3

echo "==> Extracting maintenance page..."
mkdir -p public
sudo docker compose cp app:/var/www/html/public/maintenance.html public/maintenance.html

echo "==> Running migrations..."
sudo docker compose exec -T -u www-data app php bin/console doctrine:migrations:migrate --no-interaction

echo "==> Seeding RBAC system roles (idempotent)..."
sudo docker compose exec -T -u www-data app php bin/console app:seed-rbac

echo "==> Syncing RBAC permissions catalog..."
sudo docker compose exec -T -u www-data app php bin/console app:sync-permissions

echo "==> Clearing cache..."
sudo docker compose exec -T -u www-data app php bin/console cache:clear --env=prod
sudo docker compose exec -T -u www-data app php bin/console cache:warmup --env=prod

echo "==> Checking error tracking (GlitchTip)..."
SENTRY_DSN_VALUE="$(sudo docker compose exec -T app printenv SENTRY_DSN 2>/dev/null || true)"
if [ -n "${SENTRY_DSN_VALUE}" ]; then
  echo "    SENTRY_DSN detecte — erreurs backend envoyees a GlitchTip."
else
  echo "    SENTRY_DSN absent/vide — error tracking backend desactive (ajouter SENTRY_DSN dans .env)."
fi

echo "==> Disabling maintenance mode..."
rm -f maintenance.on

VERSION=$(sudo docker compose exec -T app cat config/version.yaml | grep 'app.version' | awk -F"'" '{print $2}')
echo "==> Deployed v${VERSION}"
