#!/usr/bin/bash
# create and run clone

set -eu

show_help() {
    cat << EOF >&2
Usage: $(basename "$0") [-n] vmname"
Create a new clone, start the vm (if not yet running) and run virt-viewer.
Squid-Proxy will be started too.
User Home will be mounted on /media/USERNAME/home
    -n   new clone will be created, even if exists
    -s   qemu:///system instead of default qemu:///session
EOF
}

exit_script() {
    echo "run-vm.sh ${VM_NAME} terminated by trap!" >> "/tmp/${UID}/exit-run-vm.log"
    virsh --connect="${QEMU}" destroy "${VM_NAME}-clone"
    trap - SIGHUP SIGINT SIGTERM # clear the trap
    kill -- -$$ # Sends SIGTERM to child/sub processes
}

QEMU='qemu:///session'

NEWCLONE=0

while getopts ':ns' OPTION; do
    case "$OPTION" in
        n)
            NEWCLONE=1
            ;;
        s)
            QEMU='qemu:///system'
            ;;
        ?)
        show_help
        exit 1
        ;;
    esac
done

shift "$((OPTIND -1))"

# if less than one arguments supplied, display usage
if [[  $# -ne 1 ]] ; then
    show_help
    exit 1
fi

# sync vm-torrents and machine definition file
sudo /usr/local/bin/sync-vm.sh -t

VM_NAME=$1
VM_DIR="/tmp/${UID}/vmimages"


if [[ ! -f "/var/lib/libvirt/images/${VM_NAME}.qcow2" && ! -f "${VM_DIR}/${VM_NAME}.qcow2" ]]; then
    if [[ ! -f "/var/lib/libvirt/images/${VM_NAME}.qcow2.torrent" ]]; then
        echo "no base VM disk '${VM_NAME}.qcow2' found and/or ${VM_NAME} not found on server" >&2
        exit 1
    fi
    # sync vm-disk image by torrent 
    sudo /usr/local/bin/sync-vm.sh "${VM_NAME}"
    echo "sudo /usr/local/bin/sync-vm.sh ${VM_NAME}"
fi

echo "qcow2 seems to be available"

imgfile="/var/lib/libvirt/images/${VM_NAME}.qcow2" && [[ -f "${VM_DIR}/${VM_NAME}.qcow2" ]] && imgfile="${VM_DIR}/${VM_NAME}.qcow2"
#backingfile=$(qemu-img info -U "${imgfile}" | grep ^image: | cut -d' ' -f2)

backingfile=$(qemu-img info -U "${imgfile}" | grep "^backing file:" | cut -d ' ' -f 3) 
while [[ ! -z "${backingfile}" ]]; do 
    echo $backingfile
    if [[ ! -f "/var/lib/libvirt/images/${backingfile}" && ! -f "${VM_DIR}/${backingfile}" ]]; then
        # sync vm-disk image by torrent 
	sudo /usr/local/bin/sync-vm.sh "${backingfile//.qcow2/}"
	echo "sudo /usr/local/bin/sync-vm.sh ${backingfile//.qcow2/}"
    fi
    imgfile="/var/lib/libvirt/images/${backingfile}" && [[ -f "${VM_DIR}/${backingfile}" ]] && imgfile="${VM_DIR}/${backingfile}"
    backingfile=$(qemu-img info -U "${imgfile}" | grep "^backing file:" | cut -d ' ' -f 3) 
done

# check, if we have to start squid
if ! killall -s 0 squid; then
    echo "starting squid."
    /usr/sbin/squid -f /etc/squid/squid-usermode.conf
fi

# check, if we have to mount home
if ! findmnt "/media/${USER}/home"; then
    echo "mounting home."
    sudo mounthome.sh
fi

export XDG_CONFIG_HOME="/tmp/${UID}/.config"

if  ! virsh --connect="${QEMU}" list | grep "${VM_NAME}-clone"; then
    echo "VM not yet running. Try to clone and start."
    if [[ "${NEWCLONE}" = 1 ]] || [[ ! -f "${VM_DIR}/${VM_NAME}-clone.qcow2" ]]; then
        create-clone.sh "${VM_NAME}"
    fi
    # delete the old vm
    virsh --connect=qemu:///session undefine "${VM_NAME}-clone" || echo "${VM_NAME}-clone did not exist"
    # finally, create the new vm
    virsh --connect=qemu:///session define "${VM_DIR}/xml/${VM_NAME}-clone.xml"
    trap exit_script SIGHUP SIGINT SIGTERM
    [[ "${QEMU}" = 'qemu:///session' ]] && sudo /usr/local/bin/start-virtiofsd.sh "${VM_NAME}"
    virsh --connect="${QEMU}" start "${VM_NAME}-clone"
fi
echo "starting viewer"
virt-viewer --connect="${QEMU}" --full-screen "${VM_NAME}-clone"