#!/bin/bash

exec >> /tmp/test.txt 2>&1

PATH="/bin:/usr/bin"
DEVICE="/dev/cryptkey"
UMOUNT="/bin/umount"
MOUNT="/bin/mount"
MOUNTP="/mnt/cryptkey"
MOUNTO="-t vfat -o noatime,sync,dirsync,ro,nodev,noexec,nosuid"
# Owner file, 8 chars for compability with older DOS fs
OWNERF="keyowner"
USERSCRIPT="/usr/local/bin/keyload"

echo "$0 started at `date` with action $ACTION and device $DEVNAME"

if [ "x$DEVNAME" != "x$DEVICE" ]; then
	echo "Device $DEVNAME is not the device we're looking for"
	exit 0
fi

echo "Cryptkey action at $DEVNAME"

case "$ACTION" in
add)	
	echo "Crypt device added"
	FS_MOUNTP=`cat /etc/fstab | sed 's/^[[:space:]]*//' | grep "^$DEVNAME" | head -1 | tr -s "[:space:]" " "`
	if [ ! -z "$FS_MOUNTP" ]; then
		MOUNTP=$FS_MOUNTP
	fi
	echo "Using $MOUNTP as mount point"

	if [ ! -d "$MOUNTP" ]; then
		/bin/mkdir --mode=0755 "$MOUNTP" || ( echo "mkdir failed"; exit 1 )
	fi

	$MOUNT $MOUNTO $DEVICE $MOUNTP || ( echo "mount failed"; exit 1 )
	if [ -r "${MOUNTP}/${OWNERF}" ]; then
		OWNER=`cat ${MOUNTP}/${OWNERF} | head -1 | sed 's/\W//g'`
		echo "Owner file found, owner is $OWNER"
		getent passwd "${OWNER}" > /dev/null
		if [ $? -eq 0 ]; then
			echo "User $OWNER exists on this system"
			# We have valid username
			$UMOUNT $MOUNTP || ( echo "umount failed"; exit 1 )
			$MOUNT ${MOUNTO},uid=${OWNER},gid=${OWNER},umask=7077 $DEVICE $MOUNTP || ( echo "remount failed"; exit 1 )
			# We're done so far, let the user script load the keys
			if [ -x "$USERSCRIPT" ]; then
				su ${OWNER} -c "$USERSCRIPT add $DEVNAME" || ( echo "user-specific command failed"; exit 1 )
			fi
			echo -n "$OWNER" > /tmp/owner.tmp
		fi
	else
		echo "No owner file found"
		$UMOUNT $MOUNTP || ( echo "umount failed"; exit 1 )
	fi

	;;

remove)	
	echo "Crypt device removed"
	OWNER=`cat /tmp/owner.tmp`
	if [ ! -z "$OWNER" ] && [ -x "$USERSCRIPT" ]; then
		su ${OWNER} -c "$USERSCRIPT remove $DEVNAME" || ( echo "user-specific command failed"; exit 1 )
	fi
	$UMOUNT $MOUNTP || true
	#( echo "umount failed"; exit 1 )
	;;

*)	echo "Unhandled action"
	exit 1
	;;
esac

echo "Done at `date`"
echo ""

exit 0

