#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  mnt [-U UUID] ACTION NAME
		  mnt -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -U UUID       the id of the device under /dev/disks/by-uuid/
		  -h, --help    show this message

		  ACTION        either "up" or "down"
		  NAME          the name of the external device


		Automate mounting and unmounting encrypted files.


		Examples:

		  Mount UTCLOUD:

		    $ mnt up UTCLOUD
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'U:h' flag; do
	case "$flag" in
		U)
			UUID="$OPTARG"
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

ACTION="${1:-}"
NAME="${2:-}"

eval "$(assert-arg -- "$ACTION" 'ACTION')"
eval "$(assert-arg -- "$NAME"   'NAME')"

if [ -z "${UUID:-}" ]; then
	F="${XDG_DATA_HOME:-$HOME/.local/share}/mnt/id-mappings/$NAME"
	if [ ! -e "$F" ]; then
		printf 'Missing -U UUID, or entry in "%s".\n' "$F"
		usage >&2
		exit 2
	fi
	UUID="$(cat "$F")"
fi


up() {
	pass show disks/"$NAME" |
		head -n1 |
		tr -d '\n' |
		udisksctl unlock -b /dev/disk/by-uuid/"$UUID" --key-file=/dev/stdin
	udisksctl mount   -b /dev/mapper/luks-"$UUID"
}

down() {
	udisksctl unmount -b /dev/mapper/luks-"$UUID"
	udisksctl lock -b /dev/disk/by-uuid/"$UUID"
}

case "$ACTION" in
	up|down)
		"$ACTION"
		;;
	*)
		printf 'Unsupported ACTION: "%s".\n' "$ACTION"
esac
