#!/bin/sh
# Liara PHP platform pre-start hook — runs before the app starts, with env vars
# available. One-time init: wait for DB, generate JWT keypair, warm cache, migrate.
set -e

echo "pre-start: waiting for database..."
i=0
until php bin/console doctrine:query:sql "SELECT 1" >/dev/null 2>&1; do
    i=$((i + 1))
    if [ "$i" -ge 30 ]; then
        echo "Database not reachable after 60s — aborting." >&2
        exit 1
    fi
    echo "waiting for database... ($i)"
    sleep 2
done

# JWT keypair persists on the mounted 'jwt' disk; --skip-if-exists is idempotent.
php bin/console lexik:jwt:generate-keypair --skip-if-exists --no-interaction

php bin/console cache:clear --no-warmup
php bin/console cache:warmup

# Apply pending migrations. NOT --all-or-nothing: MariaDB auto-commits on DDL
# (CREATE/ALTER TABLE), which discards the outer transaction's savepoints and
# triggers "SAVEPOINT DOCTRINE_x does not exist" (errno 1305). Transactional DDL
# only works on engines like PostgreSQL.
php bin/console doctrine:migrations:migrate --no-interaction
