#!/bin/bash

# ==============================================================#
# File      :   nuke
# Desc      :   nuke vagrant VMs/Disks with virsh (DANGEROUS!)
# Ctime     :   2023-07-29
# Mtime     :   2025-03-21
# Path      :   vagrant/nuke
# License   :   Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright :   2018-2026  Ruohang Feng / Vonng (rh@vonng.com)
# ==============================================================#
SCRIPT_NAME="$(basename $0)"
SCRIPT_DIR="$(cd $(dirname $0) && pwd)"

# if virsh is not installed, exit
if ! command -v virsh &> /dev/null
then
    echo "virsh could not be found, exit"
    exit 1
fi

# this will destroy all vagrant VMs and Volumes, DO USE WITH CAUTION!
echo "====================================="
echo "destroy and undefine all vagrant VMs"
virsh list --all | grep "vagrant_"
virsh list --all | grep "vagrant_" | awk '{print $2}' | xargs -I {} virsh destroy {}
virsh list --all | grep "vagrant_" | awk '{print $2}' | xargs -I {} virsh undefine {}
virsh list --all | grep "vagrant_"

echo "====================================="
echo "destroy and undefine all vagrant volumes"
virsh vol-list default | grep '^ vagrant_' | awk '{print $1}'
virsh vol-list default | grep '^ vagrant_' | awk '{print $1}' | xargs -I {} virsh vol-delete --pool default {}
virsh vol-list default | grep '^ vagrant_' | awk '{print $1}'


echo "====================================="
echo "destroy ${SCRIPT_DIR}/.vagrant cache"
rm -rf "${SCRIPT_DIR}/.vagrant"