#!/bin/bash

# WebUI System Memory Usage Generator
# Generates memory usage JSON for LibrePortal dashboard

webuiSystemMemory() {
    # Get detailed memory information
    local mem_total=$(free -b | grep '^Mem:' | awk '{print $2}')
    local mem_used=$(free -b | grep '^Mem:' | awk '{print $3}')
    local mem_free=$(free -b | grep '^Mem:' | awk '{print $4}')
    local mem_available=$(free -b | grep '^Mem:' | awk '{print $7}')
    
    # Convert to GB for display
    local mem_total_gb=$(echo "scale=2; $mem_total / 1024 / 1024 / 1024" | bc -l)
    local mem_used_gb=$(echo "scale=2; $mem_used / 1024 / 1024 / 1024" | bc -l)
    local mem_free_gb=$(echo "scale=2; $mem_free / 1024 / 1024 / 1024" | bc -l)
    local mem_available_gb=$(echo "scale=2; $mem_available / 1024 / 1024 / 1024" | bc -l)
    
    # Calculate percentage
    local mem_percent=$(echo "scale=1; $mem_used / $mem_total * 100" | bc -l)
    
    # Create memory text without parentheses to avoid syntax issues
    local mem_text="$mem_used_gb GB / $mem_total_gb GB - $mem_percent%"
    
    # 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}/memory_usage.json"
    
    # Output JSON to temp file
    cat << EOF > "$temp_file"
{
  "total": $mem_total,
  "used": $mem_used,
  "free": $mem_free,
  "available": $mem_available,
  "total_gb": "$mem_total_gb",
  "used_gb": "$mem_used_gb",
  "free_gb": "$mem_free_gb",
  "available_gb": "$mem_available_gb",
  "percent": $mem_percent,
  "text": "$mem_text",
  "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
}
