#!/bin/bash

VMID="$1"

if [[ -z "$VMID" ]]; then
  echo "Usage: $0 <vmid>"
  exit 1
fi

# Get VM hostname
HOSTNAME=$(qm config "$VMID" | awk -F': ' '/^name:/{print $2}')

# Get uptime from KVM process
pid=$(pgrep -f "kvm.*-id $VMID")
if [[ -n "$pid" ]]; then
    start_time=$(ps -p "$pid" -o lstart=)
    start_epoch=$(date -d "$start_time" +%s 2>/dev/null)
    now_epoch=$(date +%s)
    uptime_sec=$((now_epoch - start_epoch))

    days=$(( uptime_sec / 86400 ))
    hours=$(( (uptime_sec % 86400) / 3600 ))
    minutes=$(( (uptime_sec % 3600) / 60 ))

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

# Get network statistics via guest agent
NETWORK_JSON=$(qm guest cmd "$VMID" network-get-interfaces 2>/dev/null)
if [[ -z "$NETWORK_JSON" || "$NETWORK_JSON" == "null" ]]; then
  echo "VM $VMID ($HOSTNAME): no guest agent or network info available"
  exit 0
fi

# Parse inbound/outbound bytes
RX_BYTES=$(echo "$NETWORK_JSON" | jq -r '[.[] | select(.statistics) | .statistics["rx-bytes"] // 0] | add')
TX_BYTES=$(echo "$NETWORK_JSON" | jq -r '[.[] | select(.statistics) | .statistics["tx-bytes"] // 0] | add')
TOTAL_BYTES=$((RX_BYTES + TX_BYTES))

# Convert to TB and GB
RX_TB=$(awk "BEGIN { printf \"%.2f\", $RX_BYTES / 1099511627776 }")
TX_TB=$(awk "BEGIN { printf \"%.2f\", $TX_BYTES / 1099511627776 }")
TOTAL_TB=$(awk "BEGIN { printf \"%.2f\", $TOTAL_BYTES / 1099511627776 }")

RX_GB=$(awk "BEGIN { printf \"%.2f\", $RX_BYTES / 1073741824 }")
TX_GB=$(awk "BEGIN { printf \"%.2f\", $TX_BYTES / 1073741824 }")
TOTAL_GB=$(awk "BEGIN { printf \"%.2f\", $TOTAL_BYTES / 1073741824 }")

# Output
echo "VM $VMID ($HOSTNAME):"
echo "  Inbound Traffic:  $RX_TB TB | $RX_GB GB"
echo "  Outbound Traffic: $TX_TB TB | $TX_GB GB"
echo "  Total Traffic:    $TOTAL_TB TB | $TOTAL_GB GB"
echo "  Uptime:           $UPTIME"
