#!/usr/bin/env sh
# TODO: This needs to be tested and also handle errors more effectively.

NETWORK_NAME="default"
MOUNTPOINT_PARENT="${HOME}/src"
REMOTE_DIRECTORY="/home/lumia/src/"

if [ "$1" = "-u" ]; then
    vm_name="$2"
    mountpoint="${MOUNTPOINT_PARENT}/${vm_name}.vm"
    if [ -z "${vm_name}" ]; then
        echo "Virtual machine name not provided."
        exit 1
    fi

    if mount | grep -q "on ${mountpoint} "; then
        echo "Unmounting ${mountpoint}."
        fusermount -u "${mountpoint}"
    fi

    if virsh list | grep -q " ${vm_name} "; then
        echo "Stopping ${vm_name}"
        virsh destroy "${vm_name}"
    fi

    if [ -d "${mountpoint}" ]; then
        echo "Deleting directory ${mountpoint}."
        rmdir "${mountpoint}"
    fi

else
    vm_name="$1"
    mountpoint="${MOUNTPOINT_PARENT}/${vm_name}.vm"
    awk_script="/${vm_name}/ && split(\$5, a, \"/\"){ print a[1] }"

    if [ -z "${vm_name}" ]; then
        echo "Virtual machine name not provided."
        exit 1
    fi

    if [ "$(virsh list | grep " ${vm_name} ")" = "" ]; then
        virsh start "${vm_name}"
    fi

    echo "Waiting for ${vm_name} to connect to the network..."
    vm_ip_address=""

    # TODO: Exit if this failes or times out.
    # TODO: This needs a proper timeout.
    while [ "${vm_ip_address}" = "" ]; do
        vm_ip_address="$(virsh net-dhcp-leases "${NETWORK_NAME}" | awk "${awk_script}")"
    done

    # TODO: Exit if this fails.
    # TODO: Make sure this directory isn't made if the vm fails to start or connect.
    mkdir -p "${mountpoint}"

    # TODO: Exit if this failes or times out.
    # TODO: This needs a proper timeout.
    echo "Attempting to mount over ssh."
    until sshfs "${vm_ip_address}:${REMOTE_DIRECTORY}" "${mountpoint}"; do
        echo "Could not connect via SSH, retrying."
        sleep 3
    done
fi
