#!/bin/bash
# check-proxmox-vms.sh
# Check all VMs in Proxmox

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Load environment
if [ -f "${PROJECT_ROOT}/.env" ]; then
    set -a
    source "${PROJECT_ROOT}/.env"
    set +a
fi

PROXMOX_PASS="${PROXMOX_ROOT_PASS:-L@kers2010}"
PROXMOX_1_URL="https://192.168.11.10:8006"
PROXMOX_2_URL="https://192.168.11.11:8006"

# Get ticket
get_ticket() {
    local api_url=$1
    local response
    response=$(curl -k -s -X POST \
        -d "username=root@pam&password=${PROXMOX_PASS}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null)
    
    if command -v jq &> /dev/null; then
        echo "${response}" | jq -r '.data.ticket // empty' 2>/dev/null
    else
        echo "${response}" | grep -o '"ticket":"[^"]*' | head -1 | cut -d'"' -f4
    fi
}

# List VMs
list_vms() {
    local api_url=$1
    local node=$2
    local ticket=$3
    
    curl -k -s -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json/nodes/${node}/qemu" 2>/dev/null | \
        jq -r '.data[] | "\(.vmid) - \(.name) - \(.status)"' 2>/dev/null | sort -n
}

main() {
    echo "=== Site 1 (ml110-01) ==="
    local ticket1
    ticket1=$(get_ticket "${PROXMOX_1_URL}")
    if [ -n "${ticket1}" ]; then
        list_vms "${PROXMOX_1_URL}" "ml110-01" "${ticket1}"
    else
        echo "Failed to authenticate"
    fi
    
    echo ""
    echo "=== Site 2 (r630-01) ==="
    local ticket2
    ticket2=$(get_ticket "${PROXMOX_2_URL}")
    if [ -n "${ticket2}" ]; then
        list_vms "${PROXMOX_2_URL}" "r630-01" "${ticket2}"
    else
        echo "Failed to authenticate"
    fi
}

main "$@"

