#!/bin/sh

#
# Standard initramfs preamble
#
prereqs()
{
	# Make sure that remoteunlock is run last before cryptroot in local-top
	for req in /scripts/local-top/*
	do
		script=$(basename $req)
		if [ $script != cryptroot ] && [ $script != remoteunlock ]
		then
			echo $script
		fi
	done
}

case $1 in
	prereqs)
		prereqs
		exit 0
		;;
esac


#
# Helper functions
#
debug_shell() {
	[ "$cryptdebug" = "true" ] && [ -f /conf/conf.d/remoteunlock_allow_debug ] && /bin/sh
}

parse_options() {
	local cryptopts
	cryptopts="$1"

	if [ -z "$cryptopts" ]; then
		return 1
	fi

	local IFS=" ,"
	for x in $cryptopts
	do
		case $x in
			debug=*)
				cryptdebug=${x#debug=}
				;;
			ip=*)
				cryptip=${x#ip=}
				;;
			route=*)
				cryptroute=${x#ip=}
				;;
		esac
	done
	return 0
}




#check boot cmdline for cryptopts and parse'em to look if we're meant to run...
for opt in $(cat /proc/cmdline)
do
	case $opt in
		cryptopts=*)
			parse_options "${opt#cryptopts=}"
			;;
	esac
done

if [ -n "$cryptip" ]
then
	debug_shell

	if [ "$cryptip" = "dhcp" ]
	then
		dhclient3
		killall -q dhclient3
		if [ -n "$cryptroute"]
		then
			route add 10.255.255.1 dev eth0
			route add default gw 10.255.255.1
		fi
	else
		ifconfig eth0 $cryptip
	fi

	mkdir -p /dev/pts
	mount -t devpts none /dev/pts
	/usr/sbin/sshd

	debug_shell
fi

exit 0
