#!/usr/bin/env sh

# Try to start named vm
# Watch `virt net-dhcp-leases default` for that vm's hostname.
# Mount it to `~/src/vm-name.vm` when it's available.

vm_name="$1"
network_name="default"
mountpoint_parent="${HOME}/src"
remote_directory="/home/lumia/src/"

mountpoint="${mountpoint_parent}/${vm_name}.vm"

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=""

while [ "${vm_ip_address}" = "" ]; do
    virsh_line=""
    virsh_line="$(virsh net-dhcp-leases "${network_name}" | grep "${vm_name}") > /dev/null"
    if [ "${virsh_line}" != "" ]; then
        vm_ip_address="$(echo "${virsh_line}" | sed "s/\\( \\)*/\\1/g" | cut -d " " -f6 | cut -d "/" -f1)" 
    fi
done

mkdir -p "${mountpoint}"

echo "Attempting to mount over ssh."
until sshfs "${vm_ip_address}:${remote_directory}" "${mountpoint}"
do
    sleep 3
    echo "An error occurred, retrying."
done
