#!/bin/bash
set -euo pipefail

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2
}

error() {
    log "ERROR: $*"
    exit 1
}

IMAGE_NAME="docker.io/library/crossplane-provider-proxmox"
IMAGE_TAR="/tmp/crossplane-cookie-fix.tar"

log "=========================================="
log "NUCLEAR IMAGE CLEANUP AND RE-IMPORT"
log "=========================================="
log ""

# 1. Remove ALL crossplane images by all possible references
log "Step 1: Removing ALL crossplane-provider-proxmox images..."
sudo ctr -n k8s.io images rm "${IMAGE_NAME}:latest" 2>/dev/null || log "  (latest not found, continuing...)"
sudo ctr -n k8s.io images rm "${IMAGE_NAME}:v1.0.0-fixed" 2>/dev/null || log "  (v1.0.0-fixed not found, continuing...)"
sudo ctr -n k8s.io images rm "sha256:5d83df9f8d127aa8988ace01254f4adbb6336f0ad59be8193349b3eacd972cfc" 2>/dev/null || log "  (old image ID not found, continuing...)"

# 2. List and remove any remaining by name pattern
log ""
log "Step 2: Finding and removing any remaining images..."
REMAINING=$(sudo ctr -n k8s.io images ls -q | grep "${IMAGE_NAME}" || true)
if [ -n "$REMAINING" ]; then
    log "  Found remaining images:"
    echo "$REMAINING" | while read -r img; do
        log "    Removing: $img"
        sudo ctr -n k8s.io images rm "$img" 2>/dev/null || true
    done
else
    log "  No remaining images found (good!)"
fi

# 3. Verify cleanup
log ""
log "Step 3: Verifying cleanup..."
REMAINING_AFTER=$(sudo ctr -n k8s.io images ls -q | grep "${IMAGE_NAME}" || true)
if [ -n "$REMAINING_AFTER" ]; then
    error "Cleanup incomplete! Remaining images: $REMAINING_AFTER"
fi
log "  ✅ All old images removed"

# 4. Import the fresh image
log ""
log "Step 4: Importing fresh image..."
if [ ! -f "${IMAGE_TAR}" ]; then
    error "Image tar file not found at ${IMAGE_TAR}"
fi
sudo ctr -n k8s.io images import "${IMAGE_TAR}"
log "  ✅ Image imported"

# 5. Verify import
log ""
log "Step 5: Verifying import..."
IMPORTED=$(sudo ctr -n k8s.io images ls -q | grep "${IMAGE_NAME}:latest" || true)
if [ -z "$IMPORTED" ]; then
    error "Image ${IMAGE_NAME}:latest not found after import!"
fi
log "  ✅ Image verified: $IMPORTED"

# 6. Show final state
log ""
log "Step 6: Final image state:"
sudo ctr -n k8s.io images ls | grep "${IMAGE_NAME}" || error "No crossplane images found!"

log ""
log "=========================================="
log "CLEANUP COMPLETE"
log "=========================================="
log ""
log "Next steps:"
log "  1. Delete the deployment to force recreation:"
log "     kubectl delete deployment crossplane-provider-proxmox -n crossplane-system"
log ""
log "  2. Reapply the provider:"
log "     kubectl apply -f crossplane-provider-proxmox/config/provider.yaml"
log ""
log "  3. Wait for pod to be ready and verify fixes are active"

