#! /bin/sh

SSH_ASK=/usr/libexec/openssh/x11-ssh-askpass
CDETACH=/usr/bin/cdetach
CATTACH=/usr/bin/cattach
CATTACH_FLAGS='-t 720 -i 360'

CRYPT_DIR="$HOME/.crypt"
MNT_NAME="$USER"

NFS_MNT_POINT="/mnt/crypt"
MNT_POINT="$HOME/crypt"
LOCKFILE="$CRYPT_DIR/.mcrypt.lockfile"
CFS_LOCKFILE="$CRYPT_DIR/.mcrypt.active"

this_host=`hostname -f`

function isX {
    test x$DISPLAY != x || return 1

    tty=`tty`
    test "x${tty##/dev/pts/}" != x$tty || return 1

    return 0
}

function showOrigin {
    cat "$CFS_LOCKFILE" | while read; do echo "| $REPLY"; done
    echo
}

function doMount {
    test -e "$CFS_LOCKFILE" && {
	host=`head -1 "$CFS_LOCKFILE"`
	if test -e "$MNT_POINT" -o "$host" != "$this_host"; then
	    echo 'Already active; giving up. Started at';
	    showOrigin
	    exit 1;
	else
	    echo 'Lockfile exists but fs does not seem to be mounted. Will delete it and continue normally'
	    rm -f "$CFS_LOCKFILE"
	fi
    }

    is_good=
    isX && test -x $SSH_ADD && {
	$SSH_ASK | $CATTACH -- $CATTACH_FLAGS $CRYPT_DIR $MNT_NAME && is_good=1
	true
    } || {
	$CATTACH $CATTACH_FLAGS $CRYPT_DIR $MNT_NAME && is_good=1
    }

    if test "$is_good"; then
	{ echo $this_host; date; } > "$CFS_LOCKFILE"
	sync
	msg="Mountpoint does not exist; waiting..."
	make_echo=
	while ! test -e "$MNT_POINT"; do
	    echo -n $msg
	    msg="."
	    make_echo=1
	    ls "${NFS_MNT_POINT=}"/   >/dev/null 2>/dev/null
	    sleep 1
	done

	test "$make_echo" && echo
    fi
}

function doUnMount {
    if ! test -e "$CFS_LOCKFILE"; then
	echo "Does not seem to be active; trying it nevertheless..."
    else
	host=`head -1 "$CFS_LOCKFILE"`
	test "$host" == "$this_host" || {
	    echo "Was not started here; giving up. Started at"
	    showOrigin
	    exit 1
	}
    fi

    $CDETACH $MNT_NAME
    rm -f "$CFS_LOCKFILE"

    sync
    msg="Mountpoint still existing; will wait"
    make_echo=
    while test -e "$MNT_POINT"; do
	echo -n $msg
	msg="."
	make_echo=1
	ls "${NFS_MNT_POINT}" >/dev/null 2>/dev/null
	sleep 1
    done

    test "$make_echo" && echo
}

which lockfile >/dev/null 2>&1 || {
    echo "The 'lockfile' program is required by this script. Please install the procmail package!";
    exit 1;
}

lockfile -r0 $LOCKFILE || { echo "Already active; giving up"; exit 1; }
trap "rm -f $LOCKFILE" EXIT

if   test "`basename $0`" == "mcrypt"; then doMount
elif test "`basename $0`" == "ucrypt"; then doUnMount
fi
