#!/usr/bin/bash
# create VM clone

set -eu

# if less or more than one arguments supplied, display usage
if [[ $# -ne 1 ]]; then
    echo "This script takes as input the name of the VM to clone"
    echo "Usage: $0 vm_name"
    exit 1
fi

# change to image-directory
cd /var/lib/libvirt/images

VM_NAME=$1

if [[ ! -f "xml/${VM_NAME}.xml" ]] || [[ ! -f "${VM_NAME}.gcow2" ]]; then
    echo "xml or qcow2 File does not exists."
    exit 1
fi

qemu-img create -f qcow2 -F qcow2 -b "${VM_NAME}.qcow2" "${VM_NAME}-clone.qcow2"

cp "xml/${VM_NAME}.xml" "xml/${VM_NAME}-clone.xml"

# and actually rename the vm: (this also updates the storage path)
sed -i "s/${VM_NAME}/${VM_NAME}-clone/" "xml/${VM_NAME}-clone.xml"

# set Username for mounting data from correct user
sed -i "s/USER/${SUDO_USER}/" "xml/${VM_NAME}-clone.xml"

# delete the old vm
virsh --connect=qemu:///system undefine "${VM_NAME}-clone" || echo "${VM_NAME}-clone did not exist"
# finally, create the new vm
virsh --connect=qemu:///system define "xml/${VM_NAME}-clone.xml"