#!/bin/bash
# Read-only DNS consistency checker for Proxmox VMs.
# Checks that every running VM's name resolves to the IP it's actually using,
# and that reverse DNS (PTR) matches the VM name. Mismatches are reported as bugs.
set -u
echo "===== VM DNS CONSISTENCY CHECK: $(hostname -s)  $(date -u +%FT%TZ) ====="
echo
echo "##### Running VMs with IPs (via guest-agent or ARP) #####"

for vmid in $(qm list 2>/dev/null | awk 'NR>1 && $4=="running" {print $1}'); do
  name=$(qm config "$vmid" 2>/dev/null | awk '/^name:/{print $2}')
  # Get the VM's net0 config to determine the bridge
  net0=$(qm config "$vmid" 2>/dev/null | awk '/^net0:/{print $0}')
  echo ""
  echo "--- VMID $vmid: $name ---"
  echo "  net0: ${net0//net0: /}"

  # Try to get IP via guest-agent
  if qm config "$vmid" 2>/dev/null | grep -q 'agent:.*enabled=1\|^agent: 1'; then
    guest_ips=$(qm guest cmd "$vmid" network-get-interfaces 2>/dev/null)
    if [ -n "$guest_ips" ]; then
      echo "  guest-agent IPs:"
      echo "$guest_ips" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    for iface in data:
        name = iface.get('name','?')
        for addr in iface.get('ip-addresses',[]):
            ip = addr.get('ip-address','')
            typ = addr.get('ip-address-type','')
            if typ == 'ipv4' and not ip.startswith('127.'):
                print(f'    {name}: {ip}')
except: pass
" 2>/dev/null
    else
      echo "  guest-agent: no response"
    fi
  else
    echo "  guest-agent: not enabled"
  fi
done
echo
echo "===== END $(hostname -s) ====="
