#!/bin/bash

# WebUI System Disk Usage Generator
# Generates disk usage JSON for LibrePortal dashboard

webuiSystemDisk() {
    # Get root disk usage
    local root_usage=$(df -h / | tail -1 | awk '{print $3 "/" $2}')
    local root_used=$(df / | tail -1 | awk '{print $3}')
    local root_total=$(df / | tail -1 | awk '{print $2}')
    local root_percent=$(df -h / | tail -1 | awk '{print $5}' | sed 's/%//')
    
    # Get Docker disk usage if Docker is available
    local docker_usage="N/A"
    local docker_used="0"
    local docker_total="100"
    local docker_percent="0"
    
    if command -v docker &> /dev/null; then
        docker_usage=$(runFileOp docker system df --format "{{.Size}}" 2>/dev/null | head -1 || echo "N/A")
        if [[ "$docker_usage" != "N/A" ]]; then
            # Convert Docker usage to GB for calculation
            docker_used=$(echo "$docker_usage" | sed 's/GB//g' | sed 's/MB//g' | awk '{print $1*1}' 2>/dev/null || echo "0")
            docker_total="100" # Assume 100GB total for Docker
            docker_percent=$(echo "scale=1; $docker_used / $docker_total * 100" | bc -l 2>/dev/null || echo "0")
        fi
    fi
    
    # Create system info directory if it doesn't exist
    local system_dir="$containers_dir/libreportal/frontend/data/system"
    createFolders "quiet" $sudo_user_name "$system_dir"
    
    # Create temp file first, then atomic move
    local temp_file="$(mktemp)"
    local final_file="${system_dir}/disk_usage.json"
    
    # Output JSON to temp file
    cat << EOF > "$temp_file"
{
  "root": {
    "used": $root_used,
    "total": $root_total,
    "percent": $root_percent,
    "text": "$root_usage ($root_percent%)"
  },
  "docker": {
    "used": $docker_used,
    "total": $docker_total,
    "percent": $docker_percent,
    "text": "$docker_usage"
  },
  "updated": "$(date -Iseconds)"
}
EOF
    
    # Atomic move to final location
    if [ $? -eq 0 ]; then
        runFileWrite "$final_file" < "$temp_file"; rm -f "$temp_file"
    else
        rm -f "$temp_file" 2>/dev/null
    fi
}
