#!/bin/bash

# Generate environment file with GPU detection results
generate_env_file() {
    # Source the box_echo function
    source /app/scripts/box_echo.sh
    
    # Write GPU detection results to .env file for the application to use
    box_echo "Writing GPU detection results to '$APP_DATA_DIR/.env' file..."
    ENV_FILE="$APP_DATA_DIR/.env"

    # Create or update the .env file with GPU variables
    {
        # Remove any existing GPU-related variables from .env file if it exists
        if [ -f "$ENV_FILE" ]; then
            grep -v "^GPU_AVAILABLE_\|^GPU_DEVICE_" "$ENV_FILE" > "${ENV_FILE}.tmp" && mv "${ENV_FILE}.tmp" "$ENV_FILE"
        fi
        
        # Add GPU detection results
        echo "# GPU Detection Results - Auto-generated by entrypoint.sh"
        echo "GPU_AVAILABLE_NVIDIA=$GPU_AVAILABLE_NVIDIA"
        echo "GPU_AVAILABLE_INTEL=$GPU_AVAILABLE_INTEL"
        echo "GPU_AVAILABLE_AMD=$GPU_AVAILABLE_AMD"
        
        # Add device paths if they exist
        [ -n "$GPU_DEVICE_NVIDIA" ] && echo "GPU_DEVICE_NVIDIA=$GPU_DEVICE_NVIDIA"
        [ -n "$GPU_DEVICE_INTEL" ] && echo "GPU_DEVICE_INTEL=$GPU_DEVICE_INTEL"
        [ -n "$GPU_DEVICE_AMD" ] && echo "GPU_DEVICE_AMD=$GPU_DEVICE_AMD"
        
    } >> "$ENV_FILE"

    box_echo "GPU environment variables written to .env file"
}
