#!/bin/sh
set -e

cd /var/www/html

# Wait for MySQL to be ready
if [ -n "${DB_HOST}" ]; then
    echo "Waiting for MySQL at ${DB_HOST}..."
    until php -r "
        try {
            new PDO(
                'mysql:host=${DB_HOST};port=${DB_PORT:-3306}',
                '${DB_USERNAME}',
                '${DB_PASSWORD}'
            );
            exit(0);
        } catch (Exception \$e) {
            exit(1);
        }
    " 2>/dev/null; do
        sleep 2
    done
    echo "MySQL is ready."
fi

# Ensure writable directories
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true
chmod -R ug+rwx storage bootstrap/cache 2>/dev/null || true

# Create storage symlink if missing
if [ ! -L public/storage ]; then
    php artisan storage:link --no-interaction 2>/dev/null || true
fi

# Optional auto-migrate (enabled in docker-compose for dev)
if [ "${RUN_MIGRATIONS}" = "true" ]; then
    php artisan migrate --force --no-interaction
fi

exec "$@"
