#!/bin/bash
# Copy cloud image from ISO storage to local-lvm storage

set -euo pipefail

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  COPY IMAGE TO local-lvm STORAGE"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

SOURCE_IMAGE="/var/lib/vz/template/iso/ubuntu-22.04-cloud.img"
TARGET_STORAGE="local-lvm"
IMAGE_NAME="ubuntu-22.04-cloud"

# Check if source exists
echo "Step 1: Checking if source image exists..."
if [ ! -f "$SOURCE_IMAGE" ]; then
    echo "❌ Source image not found: $SOURCE_IMAGE"
    exit 1
fi

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

# Check if target storage exists
echo "Step 2: Checking if target storage exists..."
if ! pvesm status | grep -q "^${TARGET_STORAGE}"; then
    echo "❌ Target storage '$TARGET_STORAGE' not found"
    exit 1
fi
echo "✅ Target storage '$TARGET_STORAGE' exists"
echo ""

# Check if image already exists in local-lvm
echo "Step 3: Checking if image already exists in local-lvm..."
if pvesm list "$TARGET_STORAGE" 2>/dev/null | grep -q "${IMAGE_NAME}"; then
    echo "⚠️  Image already exists in local-lvm"
    echo "   Skipping copy (image is ready to use)"
    exit 0
fi
echo "✅ Image not found in local-lvm (will copy)"
echo ""

# Copy image using pvesm copy
echo "Step 4: Copying image to local-lvm storage..."
echo "   This may take a few minutes for a 660MB image..."
echo ""

# Use pvesm copy to copy from local:iso/ to local-lvm
SOURCE_VOLID="local:iso/ubuntu-22.04-cloud.img"
TARGET_VOLID="${TARGET_STORAGE}:${IMAGE_NAME}.img"

echo "   Copying from $SOURCE_VOLID to $TARGET_VOLID..."
if pvesm copy "$SOURCE_VOLID" "$TARGET_VOLID" 2>&1; then
    echo "✅ Copy successful"
else
    echo "⚠️  pvesm copy failed, trying alternative method..."
    
    # Alternative: Use qm disk import with a temporary VM
    TEMP_VMID=9999
    
    # Clean up any existing temp VM
    qm destroy "$TEMP_VMID" 2>/dev/null || true
    
    # Create a temporary VM for import
    echo "   Creating temporary VM for import..."
    qm create "$TEMP_VMID" \
        --name "temp-import" \
        --memory 512 \
        --net0 virtio,bridge=vmbr0 \
        --agent enabled=1 2>/dev/null || true
    
    # Import the disk
    echo "   Importing disk..."
    if qm disk import "$TEMP_VMID" "$SOURCE_IMAGE" "$TARGET_STORAGE" --format qcow2 2>&1; then
        echo "✅ Import successful"
        # Clean up temp VM
        qm destroy "$TEMP_VMID" 2>/dev/null || true
    else
        echo "❌ Import failed"
        # Clean up temp VM
        qm destroy "$TEMP_VMID" 2>/dev/null || true
        exit 1
    fi
fi

# Verify import
echo ""
echo "Step 5: Verifying import..."
sleep 2  # Give Proxmox a moment to refresh
if pvesm list "$TARGET_STORAGE" 2>/dev/null | grep -q "${IMAGE_NAME}"; then
    echo "✅ Image found in local-lvm storage"
else
    echo "⚠️  Image copied but not visible in pvesm list yet"
    echo "   This is normal - Proxmox may need a moment to refresh"
    echo "   The image should be available shortly"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  VERIFICATION"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""
echo "Checking local-lvm storage contents..."
pvesm list "$TARGET_STORAGE" 2>/dev/null | grep -E "ubuntu-22.04|IMAGE_NAME" | head -5 || echo "Image should be available soon"
echo ""
echo "✅ Setup complete! Image should now be available in local-lvm storage."
echo ""
echo "📝 Next Steps:"
echo "   The provider will automatically discover the image when creating VMs"

