#!/usr/bin/bash

set -eu

# if less than one arguments supplied, display usage
if [[  $# -ne 1 ]]; then
    echo "This script takes as input the name of the VM " >&2
    echo "Usage: $0 vm_name" >&2
    exit 1
fi

VM_NAME="$1"

## Make sure VMs can read the base directory:
chgrp 1010 "/lmn/media/${SUDO_USER}"
chmod 0775 "/lmn/media/${SUDO_USER}"

socket="/run/user/$(id -u $SUDO_USER)/virtiofs-${VM_NAME}.sock"

#  FIXME: This does not work.  In windows, there is no virtiofs device.
#  In GNU/Linux it's only readable.
#
#if ! systemctl -q is-active virtiofs-${VM_NAME}.socket ; then
#    systemd-run --unit=virtiofs-${VM_NAME} \
#		--slice=system-virtiofs \
#		--collect \
#		--socket-property=ListenStream="$socket" \
#		--socket-property=Accept=no \
#		--socket-property=SocketMode=0700 \
#		--socket-property=SocketUser=${SUDO_USER} \
#		--property=Type=exec \
#		--property=StandardInput=socket \
#		/usr/local/bin/virtiofsd --log-level debug --sandbox none \
#		--syslog --fd=0 --shared-dir "/lmn/media/${SUDO_USER}"
#else
#    systemctl restart virtiofs-${VM_NAME}.socket
#fi

if [[ ! -S "$socket" ]] ; then
    systemd-run --unit=virtiofs-${VM_NAME} \
		--slice=system-virtiofs \
		--collect \
		--property=Type=exec \
		--property=SuccessExitStatus=1 \
		--property="ExecStopPost=rm $socket" \
		/usr/local/bin/virtiofsd --socket-path "$socket" \
		--shared-dir "/lmn/media/${SUDO_USER}"
fi
sleep 1
chown "${SUDO_USER}" "$socket"
