#!/bin/sh

# Waits until cryptroot source device is up
# (which needs some seconds, if on an usb device),
# so that it can be found, when cryptroot starts to open it.

# Most parts copied from initramfs-script "cryptroot"
# of debian cryptsetup package

# Version: Privatix 8.09.28 by Markus Mandalka

#
# Helper functions
#

message()
{
	if [ -p /dev/.initramfs/usplash_outfifo ] && [ -x /sbin/usplash_write ]; then
		usplash_write "TEXT-URGENT $@"
	else
		echo "$@" >&2
	fi
	return 0
}

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

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


	local IFS=" ,"
	for x in $cryptopts; do
		case $x in
		source=*)
			cryptsource=${x#source=}
			if [ ${cryptsource#UUID=} != $cryptsource ]; then
				cryptsource="/dev/disk/by-uuid/${cryptsource#UUID=}"
			elif [ ${cryptsource#LABEL=} != $cryptsource ]; then
				cryptsource="/dev/disk/by-label/${cryptsource#LABEL=}"
			fi
			;;
		esac
	done

	if [ -z "$cryptsource" ]; then
		message "cryptrootwait: source parameter missing"
		return 1
	fi
	return 0
}


wait_for_cryptsource()
{
	local opts
	opts="$1"

	if [ -z "$opts" ]; then
		return 0
	fi

	parse_options "$opts" || return 1

	if [ ! -e $cryptsource ] ; then
	  message "Waiting for cryptsource ..."
	
  	  # Wait for udev to be ready
	  if [ -x /sbin/udevadm ]; then
  		  /sbin/udevadm settle --timeout=30
	  elif [ -x /sbin/udevsettle ]; then
		  /sbin/udevsettle --timeout=30
	  fi

	  # If the cryptsource hasn't shown up yet, give it a little while
	  # to deal with removable devices
	  if [ ! -e $cryptsource ] ; then

		# Max delay is 60s
		slumber=60

		slumber=$(( ${slumber} * 10 ))
		while [ ! -e $cryptsource ]; do
			/bin/sleep 0.1
			slumber=$(( ${slumber} - 1 ))
			[ ${slumber} -gt 0 ] || break
		done

	  fi

	  if [ ! -e $cryptsource ]; then
		message "cryptrootwait: Timeout! Source device $cryptsource not found!"
		return 1
	  fi

        fi

}

#
# Begin real processing
#

if [ -r /conf/conf.d/cryptroot ]; then
	while read mapping; do
		wait_for_cryptsource "$mapping"
	done < /conf/conf.d/cryptroot
fi

exit 0
