#!/bin/sh
set -e

# Wait for database to be ready
if [ -n "$DATABASE_URL" ]; then
    echo "Waiting for database..."
    host=$(echo "$DATABASE_URL" | sed -n 's/.*:\/\/[^@]*@\([^:/]*\).*/\1/p')
    port=$(echo "$DATABASE_URL" | sed -n 's/.*:\([0-9]*\)\/.*/\1/p')
    [ -z "$port" ] && port=3306
    until nc -z "$host" "$port" 2>/dev/null; do
        sleep 1
    done
    echo "Database ready."
fi

# Fix permissions on persistent volume (mounted as root by Docker)
chown -R www-data:www-data /var/www/html/var

echo "Clearing cache..."
php bin/console cache:clear --no-warmup --env=prod 2>&1 || echo "WARNING: cache:clear failed (non-fatal)" >&2

echo "Warming up cache..."
php bin/console cache:warmup --env=prod 2>&1 || echo "WARNING: cache:warmup failed (non-fatal)" >&2

echo "Running migrations..."
php bin/console doctrine:migrations:migrate --no-interaction --allow-no-migration --env=prod 2>&1 || echo "WARNING: migrations failed (non-fatal)" >&2

# Rebuild cache after migrations to ensure metadata is fresh
php bin/console cache:clear --no-warmup --env=prod 2>&1 || echo "WARNING: cache:clear failed (non-fatal)" >&2
php bin/console cache:warmup --env=prod 2>&1 || echo "WARNING: cache:warmup failed (non-fatal)" >&2

# Re-fix permissions after console commands (they run as root)
chown -R www-data:www-data /var/www/html/var

echo "Starting PHP-FPM..."
exec php-fpm -F
