#!/bin/sh -e

# Need to run as normal user so that $USER works
# Use when udisks is not available in the system
#
# Usage: nmount [-u] /dev/sda1

_sudo=doas

if [ "$#" -lt 1 ]; then
    echo "Not enough arguments"
    exit 1
fi

mode='mount'
if [ "$1" = "-u" ]; then
    device="$2"
    mode='unmount'
else
    device="$1"
fi

if [ -z "$device" ]; then
    echo "Need the device name as argument."
    exit 1
fi

# Ensure the argument is a valid device
if [ -z "$(mountpoint -x "${device}")" ]; then
    echo "The argument is not a valid device"
    exit 1
fi

# Make the mount dir compatible with udisks (for Waybar's media.sh script)
parent="/run/media/$USER"
if [ "${mode}" = "mount" ]; then
    umask 0022
    device_name="${device##*/}"
    [ ! -d "${parent}" ] && ${_sudo} mkdir -p -m 0755 "${parent}"

    mount_point=$(${_sudo} mktemp -d "${parent}/${device_name}-XXXXXX")
    ${_sudo} mount -o rw,nosuid,nodev,noexec "${device}" "${mount_point}"
else
    mount_point=$(findmnt -l -o TARGET,SOURCE | grep -F "${device}" | awk '{print $1}')
    ${_sudo} umount "${device}"

    # Clean the mount point if it is in /run/media/$USER and unmounted
    if ( echo "${mount_point}" | grep -qF "${parent}" ) && [ -z "$(mountpoint -qd "${mount_point}")" ]; then
        ${_sudo} rm -rf "${mount_point}"
    fi
fi
