#!/bin/bash
# Script to fix provider image in containerd
# Removes all old images and imports the fixed one

set -e

IMAGE_TAR="/tmp/crossplane-latest-fixed.tar"

echo "=========================================="
echo "Fixing Provider Image in Containerd"
echo "=========================================="
echo ""

if [ ! -f "$IMAGE_TAR" ]; then
    echo "❌ Error: Image tar file not found: $IMAGE_TAR"
    exit 1
fi

echo "✅ Image tar file found: $IMAGE_TAR"
echo ""

echo "Step 1: Removing all old crossplane-provider-proxmox images..."
sudo ctr -n k8s.io images rm docker.io/library/crossplane-provider-proxmox:latest 2>/dev/null || echo "  (latest not found or already removed)"
sudo ctr -n k8s.io images rm docker.io/library/crossplane-provider-proxmox:v1.0.0-fixed 2>/dev/null || echo "  (v1.0.0-fixed not found or already removed)"

# Try to remove by digest if they exist
sudo ctr -n k8s.io images rm sha256:5d83df9f8d127aa8988ace01254f4adbb6336f0ad59be8193349b3eacd972cfc 2>/dev/null || echo "  (old image by digest not found)"

echo ""
echo "Step 2: Listing remaining crossplane images..."
sudo ctr -n k8s.io images ls | grep crossplane-provider-proxmox || echo "  (no crossplane images found - good!)"
echo ""

echo "Step 3: Importing the fixed image..."
if sudo ctr -n k8s.io images import "$IMAGE_TAR"; then
    echo "✅ Image imported successfully"
else
    echo "❌ Failed to import image"
    exit 1
fi

echo ""
echo "Step 4: Verifying import..."
sudo ctr -n k8s.io images ls | grep crossplane-provider-proxmox

echo ""
echo "=========================================="
echo "Image Fix Complete!"
echo "=========================================="
echo ""
echo "Next: Restart the provider pod:"
echo "  kubectl delete pod -n crossplane-system -l app=crossplane-provider-proxmox"
echo ""

