#!/bin/bash
# pve-vlan-summary.sh — group PVE QEMU VMs by VLAN across the cluster
# Run on any cluster node (or standalone). Read-only.
set -u
shopt -s nullglob

declare -A G   # sortkey -> "label|node|vmid|name|nic|bridge\n..."

for conf in /etc/pve/nodes/*/qemu-server/*.conf; do
    node=$(awk -F/ '{print $5}' <<<"$conf")
    vmid=$(basename "$conf" .conf)
    name=$(awk '/^\[/{exit} /^name:/{print $2}' "$conf")
    [ -z "$name" ] && name="-"

    # Only the active section (stop at first [snapshot] header)
    while IFS= read -r line; do
        nic=${line%%:*}
        rest=${line#*: }
        bridge=$(grep -oP 'bridge=\K[^,]+' <<<"$rest" || true); [ -z "$bridge" ] && bridge="-"
        tag=$(grep -oP 'tag=\K[^,]+' <<<"$rest" || true)
        trunks=$(grep -oP 'trunks=\K[^,]+' <<<"$rest" || true)

        if [ -n "$trunks" ]; then
            sortkey="z_trunks_$trunks"
            label="TRUNKS=$trunks"
            [ -n "$tag" ] && label="$label (native=$tag)"
        elif [ -n "$tag" ]; then
            sortkey=$(printf 'v_%05d' "$tag")
            label="VLAN $tag"
        else
            sortkey="a_untagged"
            label="UNTAGGED"
        fi
        G[$sortkey]+="$label|$node|$vmid|$name|$nic|$bridge"$'\n'
    done < <(awk '/^\[/{exit} /^net[0-9]+:/{print}' "$conf")
done

echo "=== PVE QEMU VLAN Summary ==="
echo

if [ ${#G[@]} -eq 0 ]; then
    echo "(no VM netN entries found)"
    exit 0
fi

mapfile -t keys < <(printf '%s\n' "${!G[@]}" | sort)
for k in "${keys[@]}"; do
    n=$(printf '%s' "${G[$k]}" | grep -c .)
    label=$(printf '%s' "${G[$k]}" | head -n1 | cut -d'|' -f1)
    printf '── %s  (%d iface)\n' "$label" "$n"
    printf '   %-12s %-6s %-28s %-5s %s\n' NODE VMID NAME NIC BRIDGE
    while IFS='|' read -r _ nd id nm ni br; do
        [ -z "${nd:-}" ] && continue
        printf '   %-12s %-6s %-28s %-5s %s\n' "$nd" "$id" "$nm" "$ni" "$br"
    done <<<"${G[$k]}"
    echo
done