#!/bin/bash
set -e

echo "=========================================="
echo "REMOVE OLD IMAGE BY ID"
echo "=========================================="
echo ""

OLD_IMAGE_ID="sha256:5d83df9f8d127aa8988ace01254f4adbb6336f0ad59be8193349b3eacd972cfc"
IMAGE_NAME="docker.io/library/crossplane-provider-proxmox"

echo "Step 1: Listing all crossplane images..."
sudo ctr -n k8s.io images ls | grep crossplane-provider-proxmox || echo "  (No images found)"
echo ""

echo "Step 2: Removing old image by specific ID..."
sudo ctr -n k8s.io images rm "${IMAGE_NAME}@${OLD_IMAGE_ID}" 2>&1 || echo "  (Image not found by ID)"
echo ""

echo "Step 3: Removing all images with the name (to be safe)..."
ALL_IMAGES=$(sudo ctr -n k8s.io images ls -q | grep "${IMAGE_NAME}" || true)
if [ -n "$ALL_IMAGES" ]; then
    echo "$ALL_IMAGES" | while read -r img; do
        echo "  Removing: $img"
        sudo ctr -n k8s.io images rm "$img" 2>/dev/null || true
    done
fi
echo ""

echo "Step 4: Re-importing fresh image..."
if [ ! -f /tmp/crossplane-fresh-nuclear.tar ]; then
    echo "  ❌ ERROR: Image tar not found!"
    exit 1
fi
sudo ctr -n k8s.io images import /tmp/crossplane-fresh-nuclear.tar
echo "  ✅ Image imported"
echo ""

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

echo "=========================================="
echo "OLD IMAGE REMOVAL COMPLETE"
echo "=========================================="
echo ""
echo "Now restart the pod:"
echo "  kubectl delete pod -n crossplane-system -l app=crossplane-provider-proxmox"
echo "  kubectl wait --for=condition=ready pod -n crossplane-system -l app=crossplane-provider-proxmox --timeout=120s"
echo "  kubectl logs -n crossplane-system -l app=crossplane-provider-proxmox | grep '\[FIXED CODE\]'"

