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

cd "$(dirname "$0")"

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

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

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

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

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

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

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

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

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

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