#!/bin/bash
# Verify ubuntu-22.04-cloud image availability on Proxmox nodes

set -e

echo "=== Verifying Image Availability ==="
echo ""

# Load environment variables
if [ -f .env ]; then
    source .env
else
    echo "ERROR: .env file not found"
    exit 1
fi

NODES=("ml110-01" "r630-01")
STORAGE_TYPES=("local" "local-lvm")

for NODE in "${NODES[@]}"; do
    echo "Checking node: $NODE"
    echo "----------------------------------------"
    
    # Check if node is accessible
    if ! sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "echo 'Connected'" > /dev/null 2>&1; then
        echo "  ⚠️  Cannot connect to $NODE"
        continue
    fi
    
    # Check in /var/lib/vz/template/iso
    echo "  Checking /var/lib/vz/template/iso:"
    IMAGE_PATH=$(sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "find /var/lib/vz/template/iso -name 'ubuntu-22.04-cloud.img' 2>/dev/null | head -1")
    
    if [ -n "$IMAGE_PATH" ]; then
        echo "    ✅ Found: $IMAGE_PATH"
        SIZE=$(sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "du -h '$IMAGE_PATH' | cut -f1")
        echo "    Size: $SIZE"
    else
        echo "    ❌ Not found in /var/lib/vz/template/iso"
    fi
    
    # Check in storage
    for STORAGE in "${STORAGE_TYPES[@]}"; do
        echo "  Checking storage: $STORAGE"
        STORAGE_LIST=$(sshpass -p "$PROXMOX_ROOT_PASS" ssh -o StrictHostKeyChecking=no root@$NODE "pvesm list $STORAGE 2>/dev/null | grep -i ubuntu-22.04-cloud || echo ''")
        
        if [ -n "$STORAGE_LIST" ]; then
            echo "    ✅ Found in $STORAGE:"
            echo "$STORAGE_LIST" | while read line; do
                echo "      $line"
            done
        else
            echo "    ❌ Not found in $STORAGE"
        fi
    done
    
    echo ""
done

echo "=== Summary ==="
echo ""
echo "If image is missing, download with:"
echo "  wget https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.img"
echo "  mv jammy-server-cloudimg-amd64.img /var/lib/vz/template/iso/ubuntu-22.04-cloud.img"
echo ""

