#!/bin/bash
# Quick container list script
# Simple list of all containers on Proxmox host

set +e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/load-env.sh"
load_env_file

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PORT="${PROXMOX_PORT:-8006}"

# Get first node
NODES_RESPONSE=$(curl -k -s -m 10 \
    -H "Authorization: PVEAPIToken=${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}=${PROXMOX_TOKEN_VALUE}" \
    "https://${PROXMOX_HOST}:${PROXMOX_PORT}/api2/json/nodes" 2>&1)

FIRST_NODE=$(echo "$NODES_RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin)['data'][0]['node'])" 2>/dev/null)

# Get containers
CONTAINERS_RESPONSE=$(curl -k -s -m 10 \
    -H "Authorization: PVEAPIToken=${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}=${PROXMOX_TOKEN_VALUE}" \
    "https://${PROXMOX_HOST}:${PROXMOX_PORT}/api2/json/nodes/${FIRST_NODE}/lxc" 2>&1)

echo "Containers on ${FIRST_NODE}:"
echo ""

echo "$CONTAINERS_RESPONSE" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)['data']
    if len(data) == 0:
        print('No containers found')
    else:
        print(f'{'VMID':<6} {'Name':<30} {'Status':<10}')
        print('-' * 50)
        for container in sorted(data, key=lambda x: x['vmid']):
            vmid = container['vmid']
            name = container.get('name', 'N/A')
            status = container.get('status', 'unknown')
            print(f'{vmid:<6} {name:<30} {status:<10}')
except:
    print('Failed to parse container data')
" 2>/dev/null

