#!/bin/bash

echo "VM Traffic and Uptime Report:"

for vmid in $(qm list | awk 'NR>1 {print $1}'); do
    name=$(qm config "$vmid" | grep "^name:" | awk '{print $2}')
    json=$(qm guest cmd "$vmid" network-get-interfaces 2>/dev/null)

    if [[ -z "$json" || "$json" == "null" ]]; then
        echo "VM $vmid ($name): no guest agent or network info available"
        continue
    fi

    total_bytes=$(echo "$json" | jq '[.[] | (if .statistics then ((.statistics["rx-bytes"] // 0) + (.statistics["tx-bytes"] // 0)) else 0 end)] | add')

    traffic_tb=$(awk -v bytes="$total_bytes" 'BEGIN {printf "%.2f", bytes / (1024^4)}')

    # Get VM uptime in seconds from qemu process start time
    pid=$(pgrep -f "kvm.*-id $vmid")

    if [[ -n "$pid" ]]; then
        # Get process start time in seconds since epoch
        start_time=$(ps -p "$pid" -o lstart=)
        start_epoch=$(date -d "$start_time" +%s)
        now_epoch=$(date +%s)
        uptime_sec=$((now_epoch - start_epoch))

        # Convert uptime to human-readable format
        days=$(( uptime_sec / 86400 ))
        hours=$(( (uptime_sec % 86400) / 3600 ))
        minutes=$(( (uptime_sec % 3600) / 60 ))

        uptime_str="${days}d ${hours}h ${minutes}m"
    else
        uptime_str="N/A"
    fi

    echo "VM $vmid ($name): Traffic: $traffic_tb TB, Uptime: $uptime_str"
done
