#! /bin/sh
#
# cryptodisks	Now that all block devices should be available, setup
#		encrypted block devices

CRYPTCMD=/sbin/cryptsetup
DEVMAPCMD=/sbin/dmsetup
TABFILE=/etc/crypttab
MAPPER=/dev/mapper

test -x $CRYPTCMD  || exit 0
test -x $DEVMAPCMD || exit 0
test -f $TABFILE   || exit 0             

$DEVMAPCMD mknodes

case "$1" in
start)
	echo -n "Starting crypto disks:"
	grep -v '^#' < $TABFILE | while read dst src key opt; do
		echo -n " $dst"
		if test -b $MAPPER/$dst; then
			echo -n "(running)"
		else
			echo -n "(starting)"
			if [ "x$key" != "x" ]; then
				MODE=`ls -l $key | sed 's/^....\(......\).*/\1/'`
				OWNER=`ls -l $key | sed 's/^.\{16\}\(.\{8\}\).*/\1/'`
				if test $MODE != "------" -a $key != /dev/urandom; then
					echo "INSECURE MODE FOR $key" >&2
				fi
				if test $OWNER != "root"; then
					echo "INSECURE OWNER FOR $key" >&2
				fi
				$CRYPTCMD -d $key create $dst $src
			else
				echo "..."
				$CRYPTCMD create $dst $src <&1
			fi
			if test "x$opt" = "xswap" -a -b $MAPPER/$dst; then
				echo -n "(swap)"
				mkswap $MAPPER/$dst 2>/dev/null >/dev/null
			fi
		fi
	done
	echo "."
	;;
stop)
	echo -n "Stopping crypto disks:"
	grep -v '^#' < $TABFILE | while read dst src key; do
		echo -n " $dst"
		if test -b $MAPPER/$dst; then
			if $DEVMAPCMD info $dst | grep -q '^Open count: *0$'; then
				echo -n "(stopping)"
				$CRYPTCMD remove $dst
			else
				echo -n "(busy)"
			fi
		else
			echo -n "(stopped)"
		fi
	done
	echo "."
	;;
restart|reload|force-reload)
	$0 stop
	$0 start
	;;
esac
