#!/bin/bash
# Update VMs to use local-lvm storage instead of ceph-rbd

set -euo pipefail

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  UPDATE VMs TO USE local-lvm STORAGE"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

# Find VMs configured for r630-01 with ceph-rbd storage
echo "Step 1: Finding VMs configured for r630-01 with ceph-rbd storage..."
VMS=$(kubectl get proxmoxvms -A -o json 2>/dev/null | \
    jq -r '[.items[] | 
        select(.spec.forProvider.node == "r630-01") | 
        select(.spec.forProvider.storage == "ceph-rbd") |
        select(.metadata.name != "basic-vm-001" and 
               .metadata.name != "large-vm-001" and 
               .metadata.name != "medium-vm-001" and 
               .metadata.name != "vm-100") |
        "\(.metadata.namespace)/\(.metadata.name)"
    ] | .[]')

if [ -z "$VMS" ]; then
    echo "✅ No VMs found to update (already using local-lvm or different storage)"
    exit 0
fi

VM_COUNT=$(echo "$VMS" | wc -l)
echo "Found $VM_COUNT VMs to update:"
echo "$VMS" | sed 's/^/  • /'
echo ""

# Update VMs
echo "Step 2: Updating VMs..."
UPDATED=0
FAILED=0

for VM in $VMS; do
    NAMESPACE=$(echo "$VM" | cut -d'/' -f1)
    NAME=$(echo "$VM" | cut -d'/' -f2)
    
    echo -n "Updating $VM... "
    if kubectl patch proxmoxvm -n "$NAMESPACE" "$NAME" \
        --type='json' \
        -p='[{"op": "replace", "path": "/spec/forProvider/storage", "value": "local-lvm"}]' 2>/dev/null; then
        echo "✅"
        UPDATED=$((UPDATED + 1))
    else
        echo "❌"
        FAILED=$((FAILED + 1))
    fi
done

echo ""
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  SUMMARY"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "VMs updated: $UPDATED"
echo "VMs failed: $FAILED"
echo ""
echo "✅ Update complete! VMs will now use local-lvm storage."
echo ""
echo "📝 Next Steps:"
echo "   1. Copy cloud image to local-lvm storage"
echo "   2. Monitor VM deployment: kubectl get proxmoxvms -A -w"

