#!/bin/bash
# Copy cloud image from ISO storage to image-capable storage
# This fixes the issue where images in local:iso/ cannot be used as VM disks

set -e

NODE="r630-01"
SOURCE_IMAGE="local:iso/ubuntu-22.04-cloud.img"
TARGET_STORAGE="${1:-ceph-rbd}"  # Default to ceph-rbd, or pass as first argument

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  COPY CLOUD IMAGE TO IMAGE STORAGE"
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"
    echo ""
    echo "To run remotely via SSH:"
    echo "  ssh root@192.168.11.11 'bash -s' < $0"
    echo ""
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo "Step 1: Checking if image exists in ISO storage..."
if ! pvesm list local 2>/dev/null | grep -q "ubuntu-22.04-cloud"; then
    echo "⚠️  Image not found: $SOURCE_IMAGE"
    echo "   Listing available images in local storage:"
    pvesm list local 2>/dev/null | grep -E "\.img$|\.qcow2$" | head -10 || echo "   No images found in local storage"
    exit 1
fi

echo "✅ Image found: $SOURCE_IMAGE"
echo ""

echo "Step 2: Extracting filename..."
FILENAME=$(echo "$SOURCE_IMAGE" | sed 's/.*\///')
TARGET_PATH="template/cache/$FILENAME"
TARGET_VOLID="$TARGET_STORAGE:$TARGET_PATH"

echo "   Source: $SOURCE_IMAGE"
echo "   Target: $TARGET_VOLID"
echo ""

echo "Step 3: Copying image to $TARGET_STORAGE storage..."
# Method 1: Use qm disk import (recommended)
if command -v qm &> /dev/null; then
    echo "   Using qm disk import method..."
    # Create a temporary VM to import the disk
    TEMP_VMID=9999
    echo "   Creating temporary VM (ID: $TEMP_VMID) for import..."
    qm create $TEMP_VMID --name temp-import --memory 128 --net0 virtio,bridge=vmbr0 2>/dev/null || {
        # VM might already exist, try to destroy it first
        qm destroy $TEMP_VMID 2>/dev/null || true
        sleep 2
        qm create $TEMP_VMID --name temp-import --memory 128 --net0 virtio,bridge=vmbr0 2>/dev/null || {
            echo "❌ Failed to create temporary VM"
            exit 1
        }
    }
    
    # Import the disk from ISO storage to target storage
    echo "   Importing disk from $SOURCE_IMAGE to $TARGET_STORAGE..."
    if qm disk import $TEMP_VMID $SOURCE_IMAGE $TARGET_STORAGE --format qcow2 2>&1; then
        echo "   ✅ Disk imported successfully"
        
        # Get the imported disk volid
        IMPORTED_DISK=$(qm config $TEMP_VMID 2>/dev/null | grep -E "^scsi[0-9]+:" | head -1 | cut -d: -f2 | cut -d, -f1 | tr -d ' ')
        if [ -n "$IMPORTED_DISK" ]; then
            echo "   Imported disk: $IMPORTED_DISK"
        fi
        
        # Clean up temp VM
        echo "   Cleaning up temporary VM..."
        qm destroy $TEMP_VMID 2>/dev/null || true
        echo "✅ Image copied successfully to $TARGET_STORAGE"
    else
        echo "⚠️  qm disk import failed, trying alternative method..."
        # Clean up temp VM first
        qm destroy $TEMP_VMID 2>/dev/null || true
        
        # Method 2: Use rbd import directly (for RBD storage)
        if [ "$TARGET_STORAGE" = "ceph-rbd" ] || [ "$TARGET_STORAGE" = "rbd" ]; then
            echo "   Using rbd import method for RBD storage..."
            SOURCE_PATH="/var/lib/vz/template/iso/$(basename $SOURCE_IMAGE | sed 's/local:iso\///')"
            RBD_IMAGE_NAME="template_cache_$(basename $SOURCE_IMAGE | sed 's/\.img$//' | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]_')"
            
            if [ -f "$SOURCE_PATH" ]; then
                echo "   Importing image to RBD pool 'rbd' as '$RBD_IMAGE_NAME'..."
                if rbd import "$SOURCE_PATH" "rbd/$RBD_IMAGE_NAME" --image-format 2 2>&1; then
                    echo "   ✅ Image imported to RBD pool"
                    echo "   Note: Proxmox will need to discover this image"
                    echo "   The image is now in RBD pool 'rbd' as '$RBD_IMAGE_NAME'"
                else
                    echo "❌ RBD import failed"
                    exit 1
                fi
            else
                echo "❌ Source file not found at $SOURCE_PATH"
                exit 1
            fi
        else
            # Method 3: Use direct file copy (for local storage types)
            echo "   Trying direct file copy method..."
            SOURCE_PATH="/var/lib/vz/template/iso/$(basename $SOURCE_IMAGE | sed 's/local:iso\///')"
            TARGET_DIR="/var/lib/vz/images"
            
            if [ -f "$SOURCE_PATH" ]; then
                echo "   Copying file: $SOURCE_PATH -> $TARGET_DIR/"
                mkdir -p "$TARGET_DIR" 2>/dev/null || true
                cp "$SOURCE_PATH" "$TARGET_DIR/" 2>&1 && echo "✅ File copied" || {
                    echo "❌ File copy failed"
                    exit 1
                }
            else
                echo "❌ Source file not found at $SOURCE_PATH"
                echo "   Please copy the image manually or use Proxmox web UI"
                exit 1
            fi
        fi
    fi
else
    echo "❌ qm command not found"
    exit 1
fi

echo ""
echo "Step 4: Verifying copied image..."
if pvesm list "$TARGET_STORAGE" | grep -q "$FILENAME"; then
    echo "✅ Image copied to: $TARGET_VOLID"
    echo ""
    echo "The provider can now use this image directly for VM creation."
else
    echo "⚠️  Image not found in target storage, but copy may have succeeded"
    echo "   Check manually: pvesm list $TARGET_STORAGE"
fi

echo ""
echo "✅ Setup complete!"

