#!/bin/bash
# Download Ubuntu 22.04 Cloud Image to Proxmox
# Run this on the Proxmox node or from a machine with SSH access

set -euo pipefail

PROXMOX_NODE="${1:-192.168.11.10}"
PROXMOX_PASS="${PROXMOX_PASS:-L@kers2010}"
STORAGE="${STORAGE:-local-lvm}"
IMAGE_NAME="ubuntu-22.04-server-cloudimg-amd64.img"
IMAGE_URL="https://cloud-images.ubuntu.com/releases/22.04/release/${IMAGE_NAME}"

echo "=========================================="
echo "Downloading Ubuntu 22.04 Cloud Image"
echo "=========================================="
echo ""
echo "Node: $PROXMOX_NODE"
echo "Storage: $STORAGE"
echo "Image: $IMAGE_NAME"
echo ""

# Check if image already exists
echo "Checking if image already exists..."
if sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$PROXMOX_NODE "pvesm list $STORAGE | grep -q '$IMAGE_NAME'"; then
    echo "✅ Image already exists in $STORAGE"
    exit 0
fi

# Download image to Proxmox node
echo "Downloading image to Proxmox node..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$PROXMOX_NODE "
    cd /tmp
    if [ ! -f $IMAGE_NAME ]; then
        echo 'Downloading from $IMAGE_URL...'
        wget -q --show-progress $IMAGE_URL -O $IMAGE_NAME
        echo '✅ Download complete'
    else
        echo 'Image already downloaded locally'
    fi
"

# Upload to Proxmox storage
echo ""
echo "Uploading image to Proxmox storage ($STORAGE)..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$PROXMOX_NODE "
    # Create storage path if needed
    mkdir -p /var/lib/vz/template/iso
    
    # Copy to storage
    if [ -f /tmp/$IMAGE_NAME ]; then
        echo 'Copying to storage...'
        cp /tmp/$IMAGE_NAME /var/lib/vz/template/iso/$IMAGE_NAME
        echo '✅ Image uploaded to /var/lib/vz/template/iso/$IMAGE_NAME'
        
        # Verify
        if pvesm list $STORAGE | grep -q '$IMAGE_NAME'; then
            echo '✅ Image verified in storage'
        else
            echo '⚠️  Image copied but not showing in storage list'
            echo 'You may need to refresh storage or use full path: local:$IMAGE_NAME'
        fi
    else
        echo '❌ Image file not found after download'
        exit 1
    fi
"

echo ""
echo "=========================================="
echo "✅ Ubuntu 22.04 Cloud Image Ready"
echo "=========================================="
echo ""
echo "Image location: /var/lib/vz/template/iso/$IMAGE_NAME"
echo "Use in templates as: local:$IMAGE_NAME"
echo "Or: $STORAGE:$IMAGE_NAME"
echo ""
