#!/bin/bash

# WebUI System Information Generator
# Generates system information JSON for LibrePortal dashboard

webuiSystemInfo() {
    # Get OS information - try to get distribution name
    local os_info=""
    if [ -f /etc/os-release ]; then
        os_info=$(grep '^PRETTY_NAME=' /etc/os-release | cut -d'"' -f2)
        if [ -z "$os_info" ]; then
            os_info=$(grep '^NAME=' /etc/os-release | cut -d'"' -f2)
        fi
        # Clean up the OS name to be shorter
        os_info=$(echo "$os_info" | cut -d' ' -f1)
    fi
    if [ -z "$os_info" ]; then
        os_info=$(uname -s)
    fi
    
    # Get uptime in a readable format
    local uptime_info=$(uptime -p 2>/dev/null || uptime | cut -d',' -f1 | cut -d' ' -f3-)
    
    # Get memory usage
    local memory_info=$(free -h | grep '^Mem:' | awk '{print $3 "/" $2}')
    
    # Get CPU info
    local cpu_info=$(grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2 | sed 's/^ *//')
    
    # Get kernel version
    local kernel_version=$(uname -r)
    
    # 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}/system_info.json"
    
    # Output JSON to temp file
    cat << EOF > "$temp_file"
{
  "os": "$os_info",
  "uptime": "$uptime_info",
  "memory": "$memory_info",
  "cpu": "$cpu_info",
  "kernel": "$kernel_version",
  "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
}
