#!/bin/bash
# Should be run on desktopX

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

#
# vserver2 uses a snapshot of vserver, but just shifts the MAC address.
#
# expected LVM state:
#
#     /dev/vg/vserver      exists (original install of vserver)
#     /dev/vg/vserver-snap exists (snapshot for original vserver)
#
#     we want to create:
#
#     /dev/vg/vserver2-snap    which will also be an install of vserver
#

domain=vserver2
snapdomain=vserver
snapname="${domain}-snap"
origsnapname="${snapdomain}-snap"
VG=vol0

original="/dev/${VG}/${snapdomain}"
origsnapshot="/dev/${VG}/${origsnapname}"
snapshot="/dev/${VG}/${snapname}"

snapsize=2.5G

# If the original domain does not exist, tell them to create it first
if ! virsh dominfo "${snapdomain}" >& /dev/null
then
        echo "Error: ${snapdomain} is not a valid domain name."
	echo "Create ${snapdomain} first by running /usr/local/sbin/install-vserver"
        exit 1
fi

# If the original snapshot does not exist, tell them to create it first
if ! grep "${origsnapshot}" /etc/libvirt/qemu/vserver.xml &> /dev/null
then
	echo "Error: ${origsnapshot} is not being used by vserver."
        echo "Create a snapshot first by running /usr/local/sbin/lab-resetvm"
        exit 2
fi


# Destroy the snapshot storage
if [ -e "${snapshot}" ]; then
	echo "Removing ${snapshot} logical volume." >& /dev/null
	lvremove -f "${snapshot}"
fi

# Use the same logic as install-vserver
# Lets get the last octet of the ip address.
LOOIA=$(echo "$(hostname -i | cut -d. -f4 )" | bc)

# Get X+200 and convert to hex
HEX=`echo "obase=16; $LOOIA+200"|bc`


# Configure the virtual machine to use the snapshot
echo "Configuring ${domain} to use a snapshot LV of ${snapdomain} for storage."
virsh dumpxml ${snapdomain} > /tmp/$$.xml
sed -i  \
	-e "/uuid/d" \
	-e "s/vserver/vserver2/g" \
	-e "s/mac address='52:54:00:00:00:..'/mac address='52:54:00:00:00:${HEX}'/" /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

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

exit 0

