#!/bin/bash
# Import cloud image directly to RBD pool using rbd import
# This is the correct method for copying images to ceph-rbd storage

set -e

SOURCE_IMAGE="/var/lib/vz/template/iso/ubuntu-22.04-cloud.img"
RBD_POOL="rbd"
RBD_IMAGE_NAME="template_cache_ubuntu_22_04_cloud"

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  IMPORT IMAGE TO RBD POOL"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

# Check if running on r630-01
HOSTNAME=$(hostname)
if [ "$HOSTNAME" != "r630-01" ]; then
    echo "⚠️  WARNING: This script should be run on r630-01"
    echo "   Current hostname: $HOSTNAME"
    exit 1
fi

echo "Step 1: Checking if source image exists..."
if [ ! -f "$SOURCE_IMAGE" ]; then
    echo "❌ Source image not found: $SOURCE_IMAGE"
    echo "   Available images in /var/lib/vz/template/iso/:"
    ls -lh /var/lib/vz/template/iso/*.img 2>/dev/null | head -5 || echo "   (no .img files found)"
    exit 1
fi

IMAGE_SIZE=$(du -h "$SOURCE_IMAGE" | cut -f1)
echo "✅ Source image found: $SOURCE_IMAGE ($IMAGE_SIZE)"
echo ""

echo "Step 2: Checking RBD pool..."
if ! ceph osd pool ls 2>/dev/null | grep -q "^${RBD_POOL}$"; then
    echo "❌ RBD pool '$RBD_POOL' does not exist"
    exit 1
fi
echo "✅ RBD pool '$RBD_POOL' exists"
echo ""

echo "Step 3: Checking if image already exists in RBD pool..."
if rbd ls -p "$RBD_POOL" 2>/dev/null | grep -q "^${RBD_IMAGE_NAME}$"; then
    echo "⚠️  Image '$RBD_IMAGE_NAME' already exists in RBD pool"
    echo "   Removing existing image to overwrite..."
    rbd rm -p "$RBD_POOL" "$RBD_IMAGE_NAME" 2>/dev/null || true
    echo "   ✅ Existing image removed"
fi
echo ""

echo "Step 4: Importing image to RBD pool..."
echo "   This may take a few minutes for large images..."
echo "   Source: $SOURCE_IMAGE"
echo "   Target: rbd/$RBD_IMAGE_NAME"
echo ""

if rbd import "$SOURCE_IMAGE" "${RBD_POOL}/${RBD_IMAGE_NAME}" --image-format 2 2>&1; then
    echo "✅ Image imported successfully to RBD pool"
else
    echo "❌ RBD import failed"
    exit 1
fi

echo ""
echo "Step 5: Verifying imported image..."
if rbd ls -p "$RBD_POOL" 2>/dev/null | grep -q "^${RBD_IMAGE_NAME}$"; then
    RBD_SIZE=$(rbd info -p "$RBD_POOL" "$RBD_IMAGE_NAME" 2>/dev/null | grep "size" | awk '{print $2, $3}' || echo "unknown")
    echo "✅ Image verified in RBD pool"
    echo "   Image: ${RBD_POOL}/${RBD_IMAGE_NAME}"
    echo "   Size: $RBD_SIZE"
    echo ""
    echo "⚠️  Note: Proxmox may need to refresh to see this image."
    echo "   The image is now available in the RBD pool and can be used by VMs."
    echo "   The provider will search for images in ceph-rbd storage."
else
    echo "⚠️  Image not found in RBD pool after import"
    exit 1
fi

echo ""
echo "✅ Import complete!"

