#!/bin/bash
set -e

echo "Waiting for database connection..."
# Wait for MySQL to be ready (using root user for initial connection check)
until php -r "try { \$pdo = new PDO('mysql:host=db;port=3306', 'root', getenv('MYSQL_ROOT_PASSWORD') ?: 'root'); echo 'Database connected'; exit(0); } catch (Exception \$e) { exit(1); }" 2>/dev/null; do
    echo "Database is unavailable - sleeping"
    sleep 2
done

echo "Database is up - executing commands"

# Set proper permissions (must be root to chown)
if [ "$(id -u)" = "0" ]; then
    chown -R www-data:www-data /var/www/html/storage
    chown -R www-data:www-data /var/www/html/bootstrap/cache
    chmod -R 755 /var/www/html/storage
    chmod -R 755 /var/www/html/bootstrap/cache
fi

# Install/update composer dependencies if vendor doesn't exist
if [ ! -d "vendor" ]; then
    echo "Installing composer dependencies..."
    composer install --no-interaction --prefer-dist --no-scripts
    # Fix ownership after installation
    if [ "$(id -u)" = "0" ]; then
        chown -R www-data:www-data /var/www/html/vendor
    fi
fi

# Install/update npm dependencies if node_modules doesn't exist
if [ ! -d "node_modules" ]; then
    echo "Installing npm dependencies..."
    npm install
    # Fix ownership after installation
    if [ "$(id -u)" = "0" ]; then
        chown -R www-data:www-data /var/www/html/node_modules
    fi
fi

# Clear and cache config (only if .env exists)
if [ -f ".env" ]; then
    php artisan config:clear || true
    php artisan cache:clear || true
    php artisan view:clear || true
    php artisan route:clear || true
fi

exec "$@"

