#!/bin/bash

PATH=/bin:/usr/bin:/sbin:/usr/sbin

if [ "$(id -u)" != 0 ]; then
   echo echo @@@@@@@@@@@@@@@@@@@@@@@@@ warning @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   echo $0 expects to be invoked as root.  
   echo Expect inconsistent results.
   echo @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   echo
fi

if [[ -n $1 ]];then
    domain="$1"
else
    domain=vserver
fi

# confirm that domain exists
DOMID=$(virsh domid $domain)
if [ -z $DOMID ]; then
	echo domain "$domain" not found.  exiting.
	exit 1
fi

snapname="${domain}-snap"
VG=vol0

original="/dev/${VG}/vserver"
snapshot="/dev/${VG}/${snapname}"

snapsize=2.5G

echo "Destroying ${domain} virtual machine."


# Shut down the virtual machine immediately.
# there have been reports of difficulty reseting, possbily 
# due to asynchronous destroys.  Wait for domain to die.

virsh destroy "$domain" >& /dev/null
while /bin/true; do
	DOMID=$(virsh domid "$domain")
	[ "$DOMID" = "-" ] && break
	sleep 1
	echo "waiting for domain "$domain" to terminate..."
	virsh destroy "$domain" >& /dev/null
done

# Destroy the snapshot storage
#
# again, there have been reports of difficulty reseting, possbily 
# due to failure to remove snapshot.  Wait for snapshot to 
# really be gone, if needed.
# 
# this is a known but unresovled issue, related to udev interactions :(.
# https://bugzilla.redhat.com/show_bug.cgi?id=577798
# https://www.redhat.com/archives/linux-lvm/2010-August/thread.html#00035
# --bowe
#
# noting that interacive lvremove tends be more successful, trying the 
# following tacky approach that seems to work (unless you redirect output :().
# this needs to be rewritten in python/pexpect to hide interactivity.
#
echo "Removing ${snapshot} logical volume." >& /dev/null
while [ -e $snapshot ]; do
	echo "waiting for snapshot removal"
	sleep 5
	#(sleep 2; echo y) | lvremove "$snapshot" > /dev/null
	(sleep 2; echo y) | lvremove "$snapshot"
done

# Configure the virtual machine to use the snapshot
echo "Tuning ${domain} to use a snapshot LV for storage."
virsh dumpxml ${domain} > /tmp/$$.xml
sed -i -e "s:dev='${original}':dev='${snapshot}':" /tmp/$$.xml
virsh define /tmp/$$.xml
rm -f /tmp/$$.xml

# Create a new snapshot 
echo "Creating fresh snapshot: ${snapshot}."
lvcreate -s -n "${snapname}" -L "${snapsize}" "${original}" >& /dev/null

# Shut down the virtual machine immediately.
echo "Starting new instance of ${domain} virtual machine."
virsh start "${domain}" >& /dev/null

exit 0
