#!/bin/sh
# mount things and run a shell, unmounting them when done
#
# This is a bit like the automounter, except it's all going on
# without root intervention and things work nicely with sshfs and
# ssh-agent.
#
# To use this create a file ~/.config/with/mounts with
# lines of
# <mountpoint> <mount command>
# where mount command is the command for mounting without the actual
# mountpoint, which is supposed to be the last argument.
#
# With this, say
# with mountpoint
# and end up in a shell at ~/mountpoint (which will be created and deleted
# as necessary).  Exit the shell to (try) an unmount.
#
# The script tries to set up a shell prompt and window title (where supported)
# to make locating the "mount windows" easy.  To enable this, add
#
# eval "$BASH_POST_RC"
#
# to the end of your .bashrc.

die() {
	echo $@
	exit 1
}

usage() {
	die "Usage: with <mount key> [<command-and-arguments>]"
}

cd_into=yes
while getopts "s" option
do
	case $option in
		s)
			cd_into=no
		;;
		*) 	usage
			exit 1
	esac
done
shift $((OPTIND-1))

if [ $# -lt 1 ]; then
	usage
fi
mount_label="$1"

mountspec=$(grep "^$mount_label " ~/.config/with/mounts)

if [ t"$mountspec" = t ]; then
	die "No mount config for $mount_label"
fi

mountpoint="$HOME/auto/$mount_label"
shift

if grep "$mountpoint" /proc/self/mounts >/dev/null; then
	echo "$mountpoint already mounted; not mounting"
else
	mkdir -p $mountpoint || die "Mountpoint creation failed"
	eval ${mountspec#* } $mountpoint || die "Mounting failed"
	if [ -x /usr/local/bin/mark-critical ]; then
		/usr/local/bin/mark-critical enter "$mount_label"
	fi
fi

touch $mountpoint/.with-using-$$

cleanup() {
	trap '' EXIT
	cd
	rm $mountpoint/.with-using-$$
	if ls $mountpoint/.with-using-* 2>/dev/null; then
		echo "Other clients present.  Not unmounting."
	else
		fusermount -uz $mountpoint
		rmdir $mountpoint
		if [ -x /usr/local/bin/mark-critical ]; then
			/usr/local/bin/mark-critical exit "$mount_label"
		fi
	fi
}
trap cleanup EXIT INT TERM

if [ $cd_into = "yes" ]; then
	cd $mountpoint
fi

label=$(echo $mount_label | tr "[:lower:]" "[:upper:]")
BASH_POST_RC="PS1=$label':\$PWD \\\$ '"
case "$TERM" in
xterm*|rxvt*)
    BASH_POST_RC="${BASH_POST_RC};PROMPT_COMMAND='echo -ne \"\033]0;'$label:'\${PWD}\007\"'"
    ;;
esac

export BASH_POST_RC

if [ -z "$*" ]; then
	bash
else
	"$@"
fi
