#!/bin/bash
# MbetterClient Comprehensive Compatibility Wrapper
# Automatically detects virtualization and hardware acceleration
# Applies Mesa GLX with transparency optimizations when needed

echo "=== MbetterClient Comprehensive Compatibility Wrapper ==="
echo "Detecting environment and applying optimal settings..."
echo ""

# Function to detect virtualization
detect_virtualization() {
    local VIRT_TYPE=""
    
    # VMware detection
    if [ -f "/proc/driver/vmwgfx/version" ] || \
       grep -q "VMware" /proc/scsi/scsi 2>/dev/null || \
       lspci 2>/dev/null | grep -i vmware >/dev/null 2>&1; then
        VIRT_TYPE="VMware"
    fi
    
    # VirtualBox detection
    if [ -z "$VIRT_TYPE" ]; then
        if [ -f "/proc/driver/vboxdrv" ] || \
           lsmod 2>/dev/null | grep -q vbox || \
           lspci 2>/dev/null | grep -i virtualbox >/dev/null 2>&1; then
            VIRT_TYPE="VirtualBox"
        fi
    fi
    
    # Other virtualization detection
    if [ -z "$VIRT_TYPE" ]; then
        if grep -q "QEMU" /proc/cpuinfo 2>/dev/null || \
           [ -f "/dev/kvm" ] || \
           systemd-detect-virt 2>/dev/null | grep -v "none" >/dev/null 2>&1; then
            VIRT_TYPE="Other"
        fi
    fi
    
    echo "$VIRT_TYPE"
}

# Function to test hardware acceleration
test_hw_acceleration() {
    echo "Testing hardware acceleration availability..."
    
    # Test 1: Check for NVIDIA GPU
    if command -v nvidia-smi >/dev/null 2>&1; then
        if nvidia-smi --query-gpu=name --format=csv,noheader >/dev/null 2>&1; then
            echo "✓ NVIDIA GPU detected"
            return 0
        fi
    fi
    
    # Test 2: Check for AMD GPU
    if lspci 2>/dev/null | grep -i "vga\|3d\|display" | grep -i "amd\|ati\|radeon" >/dev/null 2>&1; then
        echo "✓ AMD GPU detected"
        return 0
    fi
    
    # Test 3: Check for Intel integrated graphics
    if lspci 2>/dev/null | grep -i "vga\|3d\|display" | grep -i "intel" >/dev/null 2>&1; then
        echo "✓ Intel integrated graphics detected"
        return 0
    fi
    
    # Test 4: Try to initialize OpenGL context
    if command -v glxinfo >/dev/null 2>&1; then
        if glxinfo 2>/dev/null | grep -q "OpenGL version"; then
            echo "✓ OpenGL context available"
            return 0
        fi
    fi
    
    # Test 5: Check Vulkan availability
    if command -v vulkaninfo >/dev/null 2>&1; then
        if vulkaninfo --summary >/dev/null 2>&1; then
            echo "✓ Vulkan available"
            return 0
        fi
    fi
    
    echo "✗ No hardware acceleration detected"
    return 1
}

# Function to setup Mesa software rendering with optimizations
setup_mesa_software() {
    echo "Setting up Mesa software rendering with transparency optimizations..."
    
    # Create optimized temp directory
    USER_TEMP="$HOME/.cache/MbetterClient"
    mkdir -p "$USER_TEMP"
    
    # Redirect all temp directories
    export TMPDIR="$USER_TEMP"
    export TEMP="$USER_TEMP"
    export TMP="$USER_TEMP"
    export XDG_RUNTIME_DIR="$USER_TEMP"
    
    # Mesa software rendering optimizations
    export LIBGL_ALWAYS_SOFTWARE=1
    export MESA_GL_VERSION_OVERRIDE=3.3
    export MESA_GLSL_VERSION_OVERRIDE=330
    export LP_NUM_THREADS=$(nproc)  # Use all CPU cores
    export MESA_GLSL_CACHE_DISABLE=0  # Enable GLSL caching
    export MESA_SHADER_CACHE_DISABLE=0  # Enable shader caching
    export MESA_NO_VULKAN=1  # Disable Vulkan in Mesa

    # MESA TRANSPARENCY FIXES - Critical for overlay transparency
    export MESA_GLX_FORCE_ALPHA=1  # Force alpha channel support
    export MESA_GLX_FORCE_TRANSPARENT=1  # Force transparency support
    export QT_XCB_GL_INTEGRATION=xcb_egl  # Better transparency with Mesa
    export QT_QPA_PLATFORM=xcb  # Ensure XCB platform for transparency
    
    # Qt WebEngine configuration for software rendering
    export QTWEBENGINE_CHROMIUM_FLAGS="--no-sandbox --disable-gpu --disable-gpu-sandbox --disable-dev-shm-usage --disable-software-rasterizer --disable-accelerated-video-decode --disable-accelerated-video-encode --disable-gpu-compositing --disable-gpu-rasterization --disable-vulkan --disable-vulkan-surface --disable-features=Vulkan --user-data-dir=$USER_TEMP --enable-transparent-visuals --disable-background-timer-throttling --disable-renderer-backgrounding --disable-vulkan-fallback"

    # Qt configuration for virtualized environments
    export QT_OPENGL=software
    export QTWEBENGINE_DISABLE_SANDBOX=1
    export QT_QPA_PLATFORM=xcb
    export QT_XCB_GL_INTEGRATION=xcb_egl  # Better compatibility with Mesa
    export QT_ENABLE_HIGHDPI_SCALING=0  # Better performance
    export QT_QUICK_BACKEND=software  # Force software backend for Qt Quick
    export QT_QPA_PLATFORM_PLUGIN_PATH=""  # Let Qt find plugins automatically
    export QT_DEBUG_PLUGINS=0  # Reduce debug output
    export QT_LOGGING_RULES="qt.qpa.plugin=false"  # Reduce plugin loading messages

    # Additional video-specific settings for virtualized environments
    export QT_MULTIMEDIA_PREFERRED_PLUGINS=""  # Let Qt choose best plugin
    export QT_GSTREAMER_PLAYBIN_FLAGS=0  # Disable problematic GStreamer features
    export QT_MULTIMEDIA_DISABLE_GSTREAMER=1  # Disable GStreamer backend
    export QT_MULTIMEDIA_FORCE_FFMPEG=1  # Force FFmpeg backend
    export QT_MULTIMEDIA_DISABLE_VIDEOSINK=1  # Disable video sink in virtual environments
    
    # Vulkan disables
    export VK_ICD_FILENAMES=""
    export DISABLE_VULKAN=1
    export MESA_VK_DISABLE=1
    
    echo "✓ Mesa software rendering configured"
    echo "✓ Transparency optimizations enabled"
    echo "✓ Multi-threaded rendering: $LP_NUM_THREADS cores"
}

# Function to setup hardware acceleration
setup_hw_acceleration() {
    echo "Setting up hardware acceleration..."
    
    # Create temp directory
    USER_TEMP="$HOME/.cache/MbetterClient"
    mkdir -p "$USER_TEMP"
    
    # Minimal Chromium flags for hardware acceleration
    export QTWEBENGINE_CHROMIUM_FLAGS="--user-data-dir=$USER_TEMP"
    
    # Qt configuration for hardware
    export QT_QPA_PLATFORM=xcb
    export QT_ENABLE_HIGHDPI_SCALING=1
    
    echo "✓ Hardware acceleration enabled"
}

# Main detection and configuration logic
VIRT_TYPE=$(detect_virtualization)
HW_ACCEL=0

if [ -n "$VIRT_TYPE" ]; then
    echo "✓ Virtualization detected: $VIRT_TYPE"
    NEEDS_SOFTWARE=1
else
    echo "✓ Physical hardware detected"
    if test_hw_acceleration; then
        HW_ACCEL=1
        NEEDS_SOFTWARE=0
    else
        echo "⚠ Hardware acceleration not available or not working"
        NEEDS_SOFTWARE=1
    fi
fi

# Apply appropriate configuration
if [ $NEEDS_SOFTWARE -eq 1 ]; then
    echo ""
    echo "=== Applying Software Rendering Configuration ==="
    setup_mesa_software
    CONFIG_TYPE="Mesa Software Rendering (Optimized)"
else
    echo ""
    echo "=== Applying Hardware Acceleration Configuration ==="
    setup_hw_acceleration
    CONFIG_TYPE="Hardware Acceleration"
fi

# Final setup
echo ""
echo "=== Configuration Summary ==="
echo "Environment: $(if [ -n "$VIRT_TYPE" ]; then echo "$VIRT_TYPE VM"; else echo "Physical Hardware"; fi)"
echo "Acceleration: $(if [ $HW_ACCEL -eq 1 ]; then echo "Hardware"; else echo "Software"; fi)"
echo "Rendering: $CONFIG_TYPE"
echo "Temp Directory: $USER_TEMP"

if [ -n "$VIRT_TYPE" ]; then
    echo ""
    echo "⚠️  VIRTUALIZED ENVIRONMENT DETECTED:"
    echo "   Video playback may not be available due to graphics limitations."
    echo "   The application will run in audio-only mode if video fails."
    echo "   This is normal behavior in virtual machines."
fi

echo ""

# Verify binary exists
if [ ! -f "./MbetterClient" ]; then
    echo "ERROR: MbetterClient binary not found in current directory"
    echo "Please run this script from the directory containing MbetterClient"
    exit 1
fi

echo "Starting MbetterClient..."
echo "=========================================="

# Execute with all configured settings
exec ./MbetterClient "$@"