#!/bin/bash
# Copy cloud image from ISO storage to image-capable storage using Proxmox API
# This script uses the Proxmox API to copy the image

set -e

PROXMOX_HOST="192.168.11.11"
PROXMOX_PORT="8006"
NODE="r630-01"
SOURCE_IMAGE="local:iso/ubuntu-22.04-cloud.img"
TARGET_STORAGE="${1:-ceph-rbd}"  # Default to ceph-rbd

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  COPY IMAGE VIA PROXMOX API"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

# Get credentials from Kubernetes secret
echo "Step 1: Getting Proxmox credentials from Kubernetes..."
TOKEN=$(kubectl -n crossplane-system get secret proxmox-credentials -o jsonpath='{.data.token}' 2>/dev/null | base64 -d 2>/dev/null)
TOKENID=$(kubectl -n crossplane-system get secret proxmox-credentials -o jsonpath='{.data.tokenid}' 2>/dev/null | base64 -d 2>/dev/null)

if [ -z "$TOKEN" ] || [ -z "$TOKENID" ]; then
    echo "❌ ERROR: Could not get Proxmox credentials from Kubernetes secret"
    echo "   Make sure you're connected to the Kubernetes cluster"
    exit 1
fi

AUTH_HEADER="PVEAPIToken=${TOKENID}=${TOKEN}"

echo "✅ Credentials retrieved"
echo ""

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

echo "Step 2: Image details..."
echo "   Source: $SOURCE_IMAGE"
echo "   Target: $TARGET_VOLID"
echo ""

# Method 1: Try using storage upload with download-url
echo "Step 3: Attempting to copy via API..."
echo "   Method 1: Using storage download-url and upload..."

# Get download URL for source image
DOWNLOAD_URL_PATH="/nodes/$NODE/storage/local/download-url"
DOWNLOAD_CONFIG="{\"volid\":\"$SOURCE_IMAGE\"}"

echo "   Getting download URL..."
DOWNLOAD_RESPONSE=$(curl -k -s -X POST \
    -H "Authorization: $AUTH_HEADER" \
    -H "Content-Type: application/json" \
    -d "$DOWNLOAD_CONFIG" \
    "https://$PROXMOX_HOST:$PROXMOX_PORT/api2/json$DOWNLOAD_URL_PATH" 2>&1)

DOWNLOAD_URL=$(echo "$DOWNLOAD_RESPONSE" | jq -r '.data // empty' 2>/dev/null)

if [ -n "$DOWNLOAD_URL" ] && [ "$DOWNLOAD_URL" != "null" ]; then
    echo "   ✅ Download URL obtained: $DOWNLOAD_URL"
    
    # Upload to target storage
    UPLOAD_PATH="/nodes/$NODE/storage/$TARGET_STORAGE/upload"
    UPLOAD_CONFIG="{\"content\":\"images\",\"filename\":\"$FILENAME\",\"url\":\"$DOWNLOAD_URL\",\"format\":\"qcow2\"}"
    
    echo "   Uploading to $TARGET_STORAGE..."
    UPLOAD_RESPONSE=$(curl -k -s -X POST \
        -H "Authorization: $AUTH_HEADER" \
        -H "Content-Type: application/json" \
        -d "$UPLOAD_CONFIG" \
        "https://$PROXMOX_HOST:$PROXMOX_PORT/api2/json$UPLOAD_PATH" 2>&1)
    
    if echo "$UPLOAD_RESPONSE" | jq -e '.data' >/dev/null 2>&1; then
        echo "   ✅ Upload initiated successfully"
        echo ""
        echo "Step 4: Waiting for upload to complete..."
        echo "   (This may take a few minutes for large images)"
        echo "   Monitor progress in Proxmox Web UI or check storage content"
        echo ""
        echo "✅ Image copy initiated!"
        echo "   The image will be available at: $TARGET_VOLID"
        exit 0
    else
        echo "   ⚠️  Upload failed: $UPLOAD_RESPONSE"
    fi
else
    echo "   ⚠️  Could not get download URL: $DOWNLOAD_RESPONSE"
fi

echo ""
echo "❌ API copy methods failed"
echo ""
echo "📋 Alternative: Use manual copy via SSH"
echo "   ssh root@$PROXMOX_HOST"
echo "   bash < scripts/copy-image-to-storage.sh $TARGET_STORAGE"
echo ""
echo "   OR use Proxmox Web UI to copy the image"
exit 1

