#!/bin/bash
# Create a Proxmox template from the cloud image in local:iso/

set -euo pipefail

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  CREATE TEMPLATE FROM CLOUD IMAGE"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

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

# 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 template already exists
echo "Step 2: Checking if template already exists..."
if qm list | grep -q "^${TEMPLATE_VMID}"; then
    echo "⚠️  Template VM $TEMPLATE_VMID already exists"
    read -p "Delete and recreate? (y/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        qm destroy "$TEMPLATE_VMID" 2>/dev/null || true
        echo "✅ Old template removed"
    else
        echo "Using existing template"
        exit 0
    fi
fi
echo ""

# Create template VM
echo "Step 3: Creating template VM..."
qm create "$TEMPLATE_VMID" \
    --name "$TEMPLATE_NAME" \
    --memory 512 \
    --net0 virtio,bridge=vmbr0 \
    --agent enabled=1 \
    --template 1 2>/dev/null || true

# Import the cloud image
echo "Step 4: Importing cloud image to template..."
echo "   This will convert qcow2 to raw format for local-lvm..."
if qm disk import "$TEMPLATE_VMID" "$SOURCE_IMAGE" "$TARGET_STORAGE" --format raw 2>&1; then
    echo "✅ Image imported successfully"
else
    echo "❌ Import failed"
    qm destroy "$TEMPLATE_VMID" 2>/dev/null || true
    exit 1
fi

# Convert to template
echo ""
echo "Step 5: Converting VM to template..."
qm template "$TEMPLATE_VMID" 2>&1 || {
    echo "⚠️  Template conversion failed, but VM is ready"
}

echo ""
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  VERIFICATION"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""
echo "Template VM status:"
qm list | grep "^${TEMPLATE_VMID}" || echo "Template not found"
echo ""
echo "✅ Template created! VMs can now clone from VMID $TEMPLATE_VMID"
echo ""
echo "📝 Note: Update VM image spec to use VMID: $TEMPLATE_VMID"
echo "   Example: image: \"$TEMPLATE_VMID\""

