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

cd "$(dirname "$0")"

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

echo "==> Deploying starseed:${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
sudo chown -R www-data:www-data public

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

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 "==> 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}"
