#!/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" >&2
    echo "Usage: $0 vm_name" >&2
    exit 1
fi

# change to image-directory
cd /lmn/vm

VM_NAME=$1
VM_DIR="/tmp/${UID}/vm"
VM_XML="${VM_DIR}/${VM_NAME}-clone.xml"

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

# Create User-VM-Dir and link system VM-Images
[[ -d "${VM_DIR}" ]] || mkdir -p "${VM_DIR}"
sudo /usr/local/bin/link-images.sh

# Create backing file
cd "${VM_DIR}"
qemu-img create -f qcow2 -F qcow2 -b "${VM_NAME}.qcow2" "${VM_NAME}-clone.qcow2"

# Create machine-definition-file
cp "${VM_DIR}/${VM_NAME}.xml" "${VM_XML}"

# set VM_DIR:
sed -i "s:VMIMAGEDIR:${VM_DIR}:" "${VM_XML}"

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

# set virtiofs-Socket
sed -i "s:VIRTIOFSSOCKET:${XDG_RUNTIME_DIR}/virtiofs/${VM_NAME}-clone.sock:" "${VM_XML}"