#!/bin/bash

set -eu -o pipefail

if [[ ${EUID} -ne 0 ]]; then
    echo "This script should be run as root." > /dev/stderr
    exit 1
fi

if [[ $# -eq 0 ]]; then
    echo "No arguments supplied"
    exit 1
fi

if [[ "$1" == "--check" ]]; then
    echo "OK"
    exit 0
fi

mount_file_contents="$1"
timeout="$2" # seconds

# mount units must be named after the mount point directories they control
where=$(echo "${mount_file_contents}" | grep "^Where=" | cut -d'=' -f 2)

mount_filename=$(systemd-escape -p --suffix=mount "$where")
mount_file="/etc/systemd/system/${mount_filename}"

# cleanup any previous mount of same name (after midway box crash?)
if systemctl -q is-active "${mount_filename}"; then
    echo "Previous mount ${mount_filename} active, unmounting"
    # unmounting can fail if a user is cd'ed into the directory. if we go ahead and mount anyway, systemd says "active" because it's referring to the previous mount config
    if ! systemctl stop "${mount_filename}"; then
        echo "Failed to unmount"
        exit 2
    fi
fi

echo "$mount_file_contents" > "${mount_file}"

systemctl daemon-reload

if ! timeout "${timeout}" systemctl enable --now "${mount_filename}"; then
    echo "Failed to mount"
    exit 3
fi

echo "Mount ${mount_filename} succeeded"

# this has to be done post-mount because permissions come from the underlying mount file system and not the mount point
chmod 777 "${where}"
