#!/bin/bash
set -e

# Function to wait for a service
wait_for_service() {
    local host="$1"
    local port="$2"
    local service="$3"
    
    echo "Waiting for ${service} at ${host}:${port}..."
    while ! nc -z "$host" "$port"; do
        sleep 1
    done
    echo "${service} is ready!"
}

# Wait for dependencies if in production mode
if [ "$APP_ENV" = "production" ] || [ "$APP_ENV" = "staging" ]; then
    # Wait for Redis if configured
    if [ ! -z "$REDIS_HOST" ]; then
        wait_for_service "$REDIS_HOST" "${REDIS_PORT:-6379}" "Redis"
    fi
    
    # Wait for MySQL if configured
    if [ ! -z "$DB_HOST" ]; then
        wait_for_service "$DB_HOST" "${DB_PORT:-3306}" "MySQL"
    fi
fi

# Create necessary directories with proper permissions
mkdir -p /var/www/html/storage/browsershot
mkdir -p /var/www/html/storage/app/public
mkdir -p /var/www/html/storage/logs
mkdir -p /var/www/html/storage/framework/{cache,sessions,views}
mkdir -p /var/www/html/bootstrap/cache

# Set permissions
chown -R www-data:www-data /var/www/html/storage
chown -R www-data:www-data /var/www/html/bootstrap/cache
chmod -R 775 /var/www/html/storage
chmod -R 775 /var/www/html/bootstrap/cache

# Create Chrome directories for www-data user
mkdir -p /tmp/.X11-unix
chmod 1777 /tmp/.X11-unix
mkdir -p /home/www-data
chown -R www-data:www-data /home/www-data

# Configure Chrome for headless operation
export CHROME_DEVEL_SANDBOX=/usr/local/sbin/chrome-devel-sandbox

# Set Chrome flags for Docker environment
export CHROME_FLAGS="--no-sandbox --disable-dev-shm-usage --disable-gpu --disable-web-security --disable-features=VizDisplayCompositor"

# Install composer dependencies if they don't exist
if [ ! -d "/var/www/html/vendor" ]; then
    echo "Installing Composer dependencies..."
    cd /var/www/html
    composer install --no-dev --optimize-autoloader --no-interaction
fi

# Run migrations if in production
if [ "$APP_ENV" = "production" ] && [ "$RUN_MIGRATIONS" = "true" ]; then
    echo "Running database migrations..."
    php artisan migrate --force
fi

# Clear and optimize Laravel caches
if [ "$APP_ENV" = "production" ]; then
    echo "Optimizing Laravel..."
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    php artisan event:cache
fi

# Create health check endpoint if it doesn't exist
if [ ! -f "/var/www/html/public/health" ]; then
    echo "OK" > /var/www/html/public/health
    chown www-data:www-data /var/www/html/public/health
fi

# Test Chrome installation
echo "Testing Chrome installation..."
google-chrome-stable --version || echo "Chrome not properly installed"

# Test Puppeteer
echo "Testing Puppeteer..."
node -e "console.log('Node version:', process.version)" || echo "Node not properly installed"

echo "Starting Apache..."

# Execute the main command (typically apache2-foreground)
exec "$@"