#!/bin/bash
# Update all VMs configured for r630-01 to use ceph-rbd instead of ceph-fs

set -e

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  UPDATE VMs TO USE ceph-rbd STORAGE"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

cd "$(dirname "$0")/.." || exit 1

echo "Step 1: Finding VMs configured for r630-01 with ceph-fs 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-fs") | 
        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)"' 2>/dev/null)

if [ -z "$VMS" ]; then
    echo "✅ No VMs found with ceph-fs storage on r630-01"
    exit 0
fi

VM_COUNT=$(echo "$VMS" | wc -l)
echo "Found $VM_COUNT VMs to update:"
echo "$VMS" | while read -r vm; do
    echo "  • $vm"
done

echo ""
read -p "Update these VMs to use ceph-rbd? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

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

echo "$VMS" | while read -r vm; do
    NAMESPACE=$(echo "$vm" | cut -d'/' -f1)
    NAME=$(echo "$vm" | cut -d'/' -f2)
    
    echo "  Updating $vm..."
    if kubectl patch proxmoxvm "$NAME" -n "$NAMESPACE" --type='json' \
        -p='[{"op": "replace", "path": "/spec/forProvider/storage", "value": "ceph-rbd"}]' 2>/dev/null; then
        echo "    ✅ Updated $vm"
        ((UPDATED++)) || true
    else
        echo "    ❌ Failed to update $vm"
        ((FAILED++)) || true
    fi
done

echo ""
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  SUMMARY"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""
echo "VMs updated: $UPDATED"
echo "VMs failed: $FAILED"
echo ""
echo "✅ Update complete! VMs will now use ceph-rbd storage."
echo ""
echo "Note: Make sure ceph-rbd storage is configured in Proxmox first:"
echo "  ssh root@192.168.11.11 'bash -s' < scripts/create-ceph-rbd-storage-r630.sh"

