#!/bin/bash

# Check for VLAN ID input
if [[ -z "$1" ]]; then
    echo "Usage: $0 <vlan-id>"
    exit 1
fi

vlan_target="$1"
found=0

echo "Searching for VMs using VLAN ID: $vlan_target"
echo "-------------------------------------------"

# Cache all VM configs in one pass
qm list | awk 'NR > 1 {print $1}' | while read -r vmid; do
    config=$(qm config "$vmid")
    
    vmname=$(echo "$config" | awk '/^name:/ {print $2}')
    
    echo "$config" | grep -E '^(virtio|net|e1000|ide)[0-9]+:' | while read -r line; do
        # Extract VLAN tag from the line
        vlan=$(echo "$line" | grep -oP 'tag=\K[0-9]+')
        
        if [[ "$vlan" == "$vlan_target" ]]; then
            echo "VMID $vmid (${vmname:-N/A}): $line"
            found=1
        fi
    done
done

[[ "$found" -eq 0 ]] && echo "No VMs found with VLAN ID $vlan_target."
