#!/bin/sh

# Part of passwordless cryptofs setup in Debian Etch.
# See: http://wejn.org/how-to-make-passwordless-cryptsetup.html
# Author: Wejn <wejn at box dot cz>

if [ "x$1" = "x" -o "x$1" = "xnone" ]; then
	KEYF=root.key
else
	KEYF=$1
fi
MD=/tmp-usb-mount

echo "Trying to get the key from USB keychain ..." >&2
mkdir -p $MD
modprobe usb-storage >/dev/null 2>&1
modprobe vfat >/dev/null 2>&1
sleep 7
OPENED=0
for SFS in /sys/block/sd*; do
	DEV=`basename $SFS`
	F=$SFS/${DEV}1/dev
	if [ 0`cat $SFS/removable` -eq 1 -a -f $F ]; then
		echo "> Trying device: $DEV ..." >&2
		mount /dev/${DEV}1 $MD -t vfat -o ro 2>/dev/null
		if [ -f $MD/$KEYF ]; then
			cat $MD/$KEYF
			umount $MD 2>/dev/null
			OPENED=1
			break
		fi
		umount $MD 2>/dev/null
	fi
done

if [ $OPENED -eq 0 ]; then
	echo "FAILED to find suitable USB keychain ..." >&2
	echo -n "Try to enter your password: " >&2
	read -s -r A
	echo -n "$A"
else
	echo "Success loading keyfile from the keychain!" >&2
fi
