#!/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

    # TODO: Probably don't shut it down by default.
    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_addresses=""

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

    echo "$vm_ip_addresses"

    # TODO: Make sure this directory isn't already a mountpoint.
    # TODO: Make sure this directory isn't made if the vm fails to start or connect.
    mkdir -p "${mountpoint}" || \
        { echo "Failed to create mountpoint ${mountpoint}"; exit 1; }

    # TODO: Exit if this failes or times out.
    # TODO: This needs a proper timeout.
    echo "Attempting to mount over ssh."
    mounted='false'

    until [ $mounted = 'true' ]; do
        for ip_address in $vm_ip_addresses; do
            echo "Trying at ${ip_address}."
            if sshfs "${ip_address}:${REMOTE_DIRECTORY}" "${mountpoint}"; then
                echo "Mounted at ${mountpoint}."
                exit 0
            else
                echo "Could not connect to SSH server on ${ip_address}."
            fi
        done

        sleep 3
    done
fi
