#!/bin/bash
# List all Proxmox VMs with VMID, Name, IP Address, FQDN, and Description
# This script uses pvesh command-line tool and requires SSH access to Proxmox node

# Configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.6.247}"
PROXMOX_USER="${PROXMOX_USER:-root}"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5"

# Function to get VM config value
get_config_value() {
    local node=$1
    local vmid=$2
    local vm_type=$3
    local key=$4
    ssh $SSH_OPTS ${PROXMOX_USER}@${PROXMOX_HOST} \
        "pvesh get /nodes/${node}/${vm_type}/${vmid}/config --output-format json" 2>/dev/null | \
        grep -o "\"${key}\":\"[^\"]*\"" | cut -d'"' -f4
}

# Function to get IP address for QEMU VM
get_qemu_ip() {
    local node=$1
    local vmid=$2
    ssh $SSH_OPTS ${PROXMOX_USER}@${PROXMOX_HOST} \
        "pvesh get /nodes/${node}/qemu/${vmid}/agent/network-get-interfaces --output-format json" 2>/dev/null | \
        python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if 'result' in data:
        for iface in data['result']:
            if 'ip-addresses' in iface:
                for ip_info in iface['ip-addresses']:
                    if ip_info.get('ip-address-type') == 'ipv4' and not ip_info.get('ip-address', '').startswith('127.'):
                        print(ip_info['ip-address'])
                        sys.exit(0)
except:
    pass
" 2>/dev/null | head -1
}

# Function to get IP address for LXC container
get_lxc_ip() {
    local vmid=$1
    ssh $SSH_OPTS ${PROXMOX_USER}@${PROXMOX_HOST} \
        "pct exec ${vmid} -- hostname -I 2>/dev/null" 2>/dev/null | \
        awk '{for(i=1;i<=NF;i++) if($i !~ /^127\./) {print $i; exit}}'
}

# Print header
printf "%-6s | %-23s | %-4s | %-19s | %-23s | %s\n" "VMID" "Name" "Type" "IP Address" "FQDN" "Description"
echo "-------|-------------------------|------|-------------------|-------------------------|----------------"

# Get all nodes
NODES=$(ssh $SSH_OPTS ${PROXMOX_USER}@${PROXMOX_HOST} "pvesh get /nodes --output-format json" 2>/dev/null | \
    python3 -c "import sys, json; [print(n['node']) for n in json.load(sys.stdin)]" 2>/dev/null)

if [ -z "$NODES" ]; then
    echo "Error: Could not connect to Proxmox host ${PROXMOX_HOST}" >&2
    echo "Usage: PROXMOX_HOST=your-host PROXMOX_USER=root ./list_vms.sh" >&2
    exit 1
fi

# Process each node
for NODE in $NODES; do
    # Get QEMU VMs
    ssh $SSH_OPTS ${PROXMOX_USER}@${PROXMOX_HOST} \
        "pvesh get /nodes/${NODE}/qemu --output-format json" 2>/dev/null | \
        python3 -c "
import sys, json
try:
    vms = json.load(sys.stdin)
    for vm in sorted(vms, key=lambda x: int(x.get('vmid', 0))):
        print(f\"{vm.get('vmid')}|{vm.get('name', 'N/A')}|qemu|{NODE}\")
except:
    pass
" 2>/dev/null | while IFS='|' read -r vmid name vm_type node; do
        description=$(get_config_value "$node" "$vmid" "$vm_type" "description")
        hostname=$(get_config_value "$node" "$vmid" "$vm_type" "hostname")
        ip=$(get_qemu_ip "$node" "$vmid")
        
        description=${description:-N/A}
        fqdn=${hostname:-N/A}
        ip=${ip:-N/A}
        
        printf "%-6s | %-23s | %-4s | %-19s | %-23s | %s\n" \
            "$vmid" "$name" "QEMU" "$ip" "$fqdn" "$description"
    done
    
    # Get LXC containers
    ssh $SSH_OPTS ${PROXMOX_USER}@${PROXMOX_HOST} \
        "pvesh get /nodes/${NODE}/lxc --output-format json" 2>/dev/null | \
        python3 -c "
import sys, json
try:
    vms = json.load(sys.stdin)
    for vm in sorted(vms, key=lambda x: int(x.get('vmid', 0))):
        print(f\"{vm.get('vmid')}|{vm.get('name', 'N/A')}|lxc|{NODE}\")
except:
    pass
" 2>/dev/null | while IFS='|' read -r vmid name vm_type node; do
        description=$(get_config_value "$node" "$vmid" "$vm_type" "description")
        hostname=$(get_config_value "$node" "$vmid" "$vm_type" "hostname")
        ip=$(get_lxc_ip "$vmid")
        
        description=${description:-N/A}
        fqdn=${hostname:-N/A}
        ip=${ip:-N/A}
        
        printf "%-6s | %-23s | %-4s | %-19s | %-23s | %s\n" \
            "$vmid" "$name" "LXC" "$ip" "$fqdn" "$description"
    done
done
