#!/bin/bash
set -e

echo "🚀 Starting Laravel container setup..."

# Navigate to Laravel root
cd /var/www/html

# Detect environment - check if this is local development
IS_LOCAL=false
# Force local development mode when BUILD_ASSETS is false (our indicator for local dev)
if [ "${BUILD_ASSETS:-false}" = "false" ] || [ "${APP_ENV:-}" = "local" ]; then
    IS_LOCAL=true
    echo "🔧 Environment: Local Development"
elif [ "${APP_ENV:-}" = "production" ]; then
    IS_LOCAL=false
    echo "🔧 Environment: Production"
else
    IS_LOCAL=true
    echo "🔧 Environment: Local Development (default)"
fi

# IMPROVED QUICK FIX: For immediate PHP-FPM startup with better permission handling
if [ "${BUILD_ASSETS:-false}" = "false" ] && [ "$IS_LOCAL" = true ]; then
    echo "⚡ Quick startup mode enabled - minimal setup for PHP-FPM"
    
    # Essential PHP-FPM config only
    sed -i 's/listen = 127.0.0.1:9000/listen = 127.0.0.1:9000/' /usr/local/etc/php-fpm.d/www.conf 2>/dev/null || true
    
    # Create basic directories - use -p flag to avoid errors if they exist
    mkdir -p storage/logs storage/framework/cache storage/framework/sessions storage/framework/views bootstrap/cache 2>/dev/null || true
    
    # Safer permissions handling - only change what we can
    if [ -w storage ]; then
        chown -R www-data:www-data storage/ 2>/dev/null || true
        chmod -R 775 storage/ 2>/dev/null || true
    fi
    if [ -w bootstrap/cache ]; then
        chown -R www-data:www-data bootstrap/cache/ 2>/dev/null || true
        chmod -R 775 bootstrap/cache/ 2>/dev/null || true
    fi
    
    echo "✅ Quick setup complete. Starting PHP-FPM..."
    echo "🔒 Starting PHP-FPM as root (worker processes will run as www-data)..."
    exec "$@"
fi

# Create necessary directories for Laravel that we can control
echo "📁 Setting up Laravel directories..."
mkdir -p storage/logs storage/framework/{cache,sessions,views} bootstrap/cache

if [ "$IS_LOCAL" = true ]; then
    # LOCAL DEVELOPMENT SETUP
    echo "🔧 Applying local development configuration..."
    
    # Configure PHP-FPM for Docker inter-container communication
    sed -i 's/listen = 127.0.0.1:9000/listen = 127.0.0.1:9000/' /usr/local/etc/php-fpm.d/www.conf 2>/dev/null || true
    sed -i 's/pm.max_children = 5/pm.max_children = 20/' /usr/local/etc/php-fpm.d/www.conf 2>/dev/null || true
    
    # Local permissions (more permissive but safer)
    echo "✏️ Setting permissions for local development..."
    # Only change permissions on directories we can write to
    if [ -w storage ]; then
        chown -R www-data:www-data storage/ 2>/dev/null || echo "Could not change ownership of storage/"
        chmod -R 775 storage/ 2>/dev/null || echo "Could not set permissions on storage/"
    else
        echo "⚠️ Storage directory not writable - using Docker volumes or host permissions"
    fi
    
    if [ -w bootstrap/cache ]; then
        chown -R www-data:www-data bootstrap/cache/ 2>/dev/null || echo "Could not change ownership of bootstrap/cache/"
        chmod -R 775 bootstrap/cache/ 2>/dev/null || echo "Could not set permissions on bootstrap/cache/"
    else
        echo "⚠️ Bootstrap cache directory not writable - using Docker volumes or host permissions"
    fi
    echo "✅ Permissions set successfully"
    
    # Asset Building for local development (disabled by default to prevent startup issues)
    if [ "${BUILD_ASSETS:-false}" = "true" ]; then
        echo "🎨 Building assets with Laravel Mix..."
        echo "📦 Installing npm dependencies..."
        timeout 120 npm install --no-audit --no-fund 2>/dev/null || echo "⚠️ NPM install failed or timed out, continuing..."
        
        echo "🔨 Building assets for development..."
        timeout 60 npm run dev 2>/dev/null || echo "⚠️ Asset build failed or timed out, continuing..."
        echo "✅ Asset building complete!"
    else
        echo "⏭️ Skipping asset building (set BUILD_ASSETS=true to enable)"
    fi
    
else
    # PRODUCTION SETUP
    echo "🔧 Running as root - setting comprehensive permissions..."
    
    # Configure PHP-FPM for production Docker inter-container communication
    echo "🔧 Configuring PHP-FPM for production..."
    sed -i 's/listen = 127.0.0.1:9000/listen = 127.0.0.1:9000/' /usr/local/etc/php-fpm.d/www.conf 2>/dev/null || true
    sed -i 's/pm.max_children = 5/pm.max_children = 50/' /usr/local/etc/php-fpm.d/www.conf 2>/dev/null || true
    sed -i 's/pm.max_children = 20/pm.max_children = 50/' /usr/local/etc/php-fpm.d/www.conf 2>/dev/null || true
    
    # Check if we're running as root or www-data
    if [ "$(id -u)" -eq 0 ]; then
        # Create shared group if it doesn't exist
        groupadd -f seraph-app 2>/dev/null || true
        
        # Add www-data to the shared group
        usermod -a -G seraph-app www-data 2>/dev/null || true
        
        # Set ownership to www-data with shared group (safer approach)
        echo "👤 Setting ownership to www-data with shared group..."
        
        # Try to set ownership on the whole project, but don't fail if we can't
        if chown -R www-data:seraph-app /var/www/html 2>/dev/null; then
            echo "✅ Successfully set ownership on entire project"
        else
            echo "⚠️  Could not change ownership of mounted files (this is normal for mounted volumes)"
            echo "   Setting permissions on directories we can control..."
            chown -R www-data:seraph-app storage/ bootstrap/cache/ 2>/dev/null || echo "Using volume permissions"
        fi
        
        # Set proper permissions - use timeout to prevent hanging
        echo "📄 Setting file permissions to 644..."
        timeout 60 find /var/www/html -type f -exec chmod 644 {} \; 2>/dev/null || echo "File permissions set with warnings"
        
        echo "📁 Setting directory permissions to 755..."
        timeout 60 find /var/www/html -type d -exec chmod 755 {} \; 2>/dev/null || echo "Directory permissions set with warnings"
        
        # Special permissions for writable directories (essential for Laravel)
        echo "✏️ Setting writable permissions for Laravel directories..."
        if [ -d "storage" ]; then
            chmod -R 775 storage/ 2>/dev/null || echo "Storage permissions set with warnings"
        fi
        if [ -d "bootstrap/cache" ]; then
            chmod -R 775 bootstrap/cache/ 2>/dev/null || echo "Bootstrap cache permissions set with warnings"
        fi
        
        # Ensure specific public directory permissions (if we can write to it)
        if [ -w public ]; then
            echo "🌐 Setting public directory permissions..."
            timeout 30 find public -type f -exec chmod 644 {} \; 2>/dev/null || echo "Public files permissions set with warnings"
            timeout 30 find public -type d -exec chmod 755 {} \; 2>/dev/null || echo "Public directories permissions set with warnings"
        fi
        
        # Set setgid bit on directories for proper group inheritance
        echo "🔒 Setting setgid bit on writable directories..."
        if [ -d "storage" ]; then
            find storage -type d -exec chmod g+s {} \; 2>/dev/null || true
        fi
        if [ -d "bootstrap/cache" ]; then
            find bootstrap/cache -type d -exec chmod g+s {} \; 2>/dev/null || true
        fi
        
    else
        echo "👤 Running as www-data user - setting limited permissions..."
        echo "   Can only modify directories we own..."
        
        # Only set permissions on directories we can control
        chmod -R 775 storage/ 2>/dev/null || true
        chmod -R 775 bootstrap/cache/ 2>/dev/null || true
        
        echo "   If you need full permission control, run container as root or set host permissions"
    fi
fi

# Make sure storage symlink exists and has correct permissions
echo "🔗 Checking storage symlink..."
if [ ! -e "public/storage" ] || [ ! -L "public/storage" ]; then
    echo "Creating storage symlink..."
    rm -rf public/storage 2>/dev/null || true # prevent Laravel error
    timeout 30 php artisan storage:link 2>/dev/null || {
        echo "⚠️  Could not create storage symlink - may need to run as root or check permissions"
    }
else
    echo "✅ Storage symlink already exists"
fi

# If .env is missing, copy from .env.demo or .env.example
if [ ! -f ".env" ]; then
  if [ -f ".env.demo" ]; then
    echo "📄 Copying .env.demo to .env..."
    cp .env.demo .env 2>/dev/null || echo "⚠️  Could not copy .env.demo file"
  elif [ -f ".env.example" ]; then
    echo "📄 Copying .env.example to .env..."
    cp .env.example .env 2>/dev/null || echo "⚠️  Could not copy .env file"
  fi
fi

# Generate APP_KEY if missing
if ! grep -q "APP_KEY=base64:" .env 2>/dev/null; then
    echo "🔑 Generating application key..."
    timeout 30 php artisan key:generate --force 2>/dev/null || echo "⚠️  Could not generate application key"
fi

# Clear Laravel caches to ensure proper asset loading (with better error handling)
echo "🧹 Clearing Laravel caches..."
timeout 10 php artisan config:clear 2>/dev/null || echo "⚠️ Config clear skipped"
timeout 10 php artisan route:clear 2>/dev/null || echo "⚠️ Route clear skipped"
timeout 10 php artisan view:clear 2>/dev/null || echo "⚠️ View clear skipped"
timeout 10 php artisan cache:clear 2>/dev/null || echo "⚠️ Cache clear skipped"
echo "✅ Cache clearing completed"

if [ "$IS_LOCAL" = false ]; then
    # Optimize Laravel for production
    echo "⚡ Optimizing Laravel for production..."
    timeout 30 php artisan config:cache 2>/dev/null || echo "⚠️  Could not cache config"
    timeout 30 php artisan route:cache 2>/dev/null || echo "⚠️  Could not cache routes"
    timeout 30 php artisan view:cache 2>/dev/null || echo "⚠️  Could not cache views"
    echo "✅ Production optimization completed"
fi

# Optional DB migrations
if [ "$RUN_MIGRATIONS" = "true" ]; then
    echo "🗄️ Running migrations..."
    timeout 120 php artisan migrate --force 2>/dev/null || echo "⚠️  Could not run migrations"
fi

if [ "$IS_LOCAL" = true ]; then
    echo "✅ Local development setup complete. Starting PHP-FPM..."
else
    echo "✅ Production setup complete. Starting PHP-FPM..."
fi

# Start PHP-FPM in foreground mode with better error handling
echo "🔒 Starting PHP-FPM with proper user management..."
echo "📝 PHP-FPM configuration test..."
if ! php-fpm -t; then
    echo "❌ PHP-FPM configuration test failed!"
    exit 1
fi

echo "✅ PHP-FPM configuration is valid"

# Ensure PHP-FPM starts successfully in local development
if [ "$IS_LOCAL" = true ]; then
    echo "🚀 Starting PHP-FPM for local development..."
    echo "🔧 Current user: $(whoami) (UID: $(id -u))"
    # Start PHP-FPM directly without gosu for local development
    exec php-fpm --nodaemonize --fpm-config /usr/local/etc/php-fpm.conf
else
    echo "🚀 Starting PHP-FPM for production..."
    # For production, use gosu to drop privileges
    if [ "$(id -u)" -eq 0 ]; then
        echo "🔧 Dropping privileges from root to www-data..."
        exec gosu www-data php-fpm --nodaemonize --fpm-config /usr/local/etc/php-fpm.conf
    else
        echo "🔧 Running as current user..."
        exec php-fpm --nodaemonize --fpm-config /usr/local/etc/php-fpm.conf
    fi
fi
