#!/bin/bash
# Lima cleanup script for kernel testing.
#
# Referenced from .cui-cui.toml as:
#   cleanup = "@runners/lima-cleanup.sh"
#
# This script runs via trap EXIT, so it executes on success, failure,
# and signals (SIGINT, SIGTERM). Keep it idempotent.

LIMA_IMAGES_PATH="${LIMA_IMAGES_PATH:-$HOME/.cache/cui-cui/lima-images}"

slugify() {
    echo "$1" | sed -E 's/[^a-zA-Z0-9]+/-/g' | tr A-Z a-z
}

INSTANCE=$(slugify "${CI_JOB_NAME}")
VM_WORK_DIR="$LIMA_IMAGES_PATH/$INSTANCE"

# Remove per-job work dir (kexec kernel, etc.)
if [ -d "$VM_WORK_DIR" ]; then
    rm -rf "$VM_WORK_DIR"
fi

# Stop and delete the VM instance
limactl stop "$INSTANCE" 2>/dev/null || true
limactl delete "$INSTANCE" 2>/dev/null || true
