#!/bin/sh

three_dots() {
	printf '.'
	sleep 0.01
	printf '.'
	sleep 0.01
	printf '.\n'
}

vmname="$1"

if echo "$vmname" | grep -vqE '^(cvm|capsul)-[a-z0-9]{10}$'; then
  echo "vmname $vmname must match "'"^capsul-[a-z0-9]{10}$"'
  exit 1
fi

echo "deleting $vmname:"
count=$(ls /tank/vm/$vmname* 2> /dev/null | wc -l)
if [ "$count" -gt 3 ]; then
	echo "too many files found, exiting cowardly:"
	echo "$(ls /tank/vm/$vmname*)"
	exit 1
fi

virsh list --name --all | grep -q -E "^$vmname$"
if [ "$?" -eq 1 ]; then
	echo "Error: $vmname not found"
	exit 1
fi

virsh list --name --state-running | grep -q -E "^$vmname$"
if [ "$?" -eq 0 ]; then
	printf '  stopping vm'; three_dots
	virsh destroy "$vmname" > /dev/null
fi

printf '  undefining xml.'; three_dots
if ! [ -f "/tank/vm/$vmname.qcow2" ]; then
	echo "/tank/vm/$vmname.qcow2 is not a file, exiting cowardly"
	exit 1
fi

virsh undefine "$vmname" > /dev/null
printf '  deleting disks.' ; three_dots
rm /tank/vm/$vmname*

echo "success"