#!/bin/bash

# Function to report CPU and memory usage from each HMC.
Report() {
    for hmc in {abr-hmc,msp-hmc,den-hmc}; do  # Loop through each HMC.
        ssh "$hmc" 'for cec in $(lssyscfg -r sys -F name | sort); do  # SSH into each HMC and get the list of CECs.
            CPU="$(lshwres -m $cec -r proc --level sys -F configurable_sys_proc_units)"  # Get total configurable CPU units.
            Avail_CPU="$(lshwres -m $cec -r proc --level sys -F curr_avail_sys_proc_units)"  # Get currently available CPU units.
            MEM="$(lshwres -m $cec -r mem --level sys -F configurable_sys_mem)"  # Get total configurable memory.
            Avail_MEM="$(lshwres -m $cec -r mem --level sys -F curr_avail_sys_mem)"  # Get currently available memory.
            echo "$cec $CPU $Avail_CPU $MEM $Avail_MEM"  # Output the CEC name, total and available CPU and memory.
        done'
    done
}

# Determine the format based on whether the output is to a terminal or a pipe/file.
if [ -t 0 ]; then
    hfmt="%-35s%15s%15s%15s%15s%15s%15s\n"  # Human-readable format for terminal output.
    fmt="%-35s%15s%15s%15.1f%15.1f%15.1f%15.1f\n"  # Format string for numeric values.
else
    hfmt="%s,%s,%s,%s,%s,%s,%s\n"  # CSV format for non-terminal output (e.g., pipe/file).
    fmt="%s,%s,%s,%.1f,%.1f,%.1f,%.1f\n"  # CSV format for numeric values.
fi

# Print the header line using the appropriate format.
printf "$hfmt" "CEC" "CPU" "Avail CPU" "CPU % Used" "MEM (GB)" "Avail MEM" "MEM % Used"

# Call the Report function and process its output.
Report | awk -v fmt="$fmt" '{
    # Calculate CPU and memory usage percentages and print the formatted output.
    printf fmt, $1, $2, $3, ($2-$3)/$2*100, $4/1024, $5/1024, ($4-$5)/$4*100
}' | sort | uniq  # Sort and remove duplicate entries.