#!/bin/sh
set -e

# Volume-mounted dirs (jwt_keys, uploads) are created/owned by root on first run.
# Ensure the runtime user can write to them. Runs every start; cheap and idempotent.
chown -R www-data:www-data var public/uploads config/jwt 2>/dev/null || true

# One-time init tasks — only the web service runs these (RUN_INIT=1).
# Workers set RUN_INIT=0 so DB migrations / JWT generation don't race.
if [ "${RUN_INIT:-1}" = "1" ]; then
    # MariaDB is a SEPARATE Coolify resource now, so there is no compose
    # depends_on: service_healthy gate. Wait for it to accept connections
    # (up to ~60s) before migrating, otherwise the first boot races the DB.
    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

    # Generate JWT keypair if not already persisted on the jwt_keys volume.
    php bin/console lexik:jwt:generate-keypair --skip-if-exists --no-interaction

    # Rebuild the prod cache (vendor was installed with --no-scripts at build time).
    php bin/console cache:clear --no-warmup
    php bin/console cache:warmup

    # Apply pending migrations. --all-or-nothing wraps them in a transaction.
    php bin/console doctrine:migrations:migrate --all-or-nothing --no-interaction
fi

exec "$@"
