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

set -eu

NEWCLONE=0

show_help() {
    cat << EOF
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
EOF
}

NEWCLONE=0

while getopts ':n' OPTION; do
    case "$OPTION" in
	n)
	    NEWCLONE=1
	    ;;
	?)
	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

VM_NAME=$1

if [[ ! -f "/var/lib/libvirt/images/${VM_NAME}.qcow2" ]]; then
    echo "no base VM disk '${VM_NAME}.qcow2' found"
    exit 1
fi

# check, if we have to start squid
if [[ ! -f "/tmp/squid.pid" ]]; then
    echo "starting squid."
    /usr/sbin/squid -f /etc/squid/squid-usermode.conf
fi

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

if  ! virsh --connect=qemu:///system list | grep "${VM_NAME}"; then
    echo "VM not yet running. Try to clone and start."
    if [[ "${NEWCLONE}" = 1 ]] || [[ ! -f "/var/lib/libvirt/images/${VM_NAME}-clone.qcow2" ]]; then
        sudo create-clone.sh "${VM_NAME}"
    fi
    virsh --connect=qemu:///system start "${VM_NAME}-clone"
fi
echo "starting viewer"
virt-viewer --connect=qemu:///system --full-screen "${VM_NAME}-clone"