#!/bin/sh

CRYPTLOG="/run/initramfs/opencrypt.log"
TMPCRYPTLOG="${CRYPTLOG}.tmp"
CONFFILE="/etc/opencrypt/opencrypt.conf"
LOCALPREFIX="localfile$$"

. /usr/share/opencrypt/functions.sh
. /usr/share/opencrypt/script-functions.sh

cryptlog() {
	echo "$@"
}

# some tools such as wpasupplicant and thus configure_networking troncates stdout
# so we use a temp logfile for them and copy back in official logfile
copy_tmp_log() {
	if [ -s "$TMPCRYPTLOG" ]; then
		if [ "$VERBOSE" = "yes" ]; then
			echo '-------------------'
			cat "$TMPCRYPTLOG"
			echo '-------------------'
		fi
		rm "$TMPCRYPTLOG"
	fi
}

open_map() {
	local status options
	rm -f "genkey-${MAP}.key"

	OPEN="false"
		scan_devices
		create_hash
		if [ ! -s "$HASH" ]; then
			scan_network
			create_hash
		fi
		if [ -s "$HASH" ]; then
			cryptlog "created key for ${MAP} in genkey-${MAP}.key"
			cat "$HASH" > "genkey-${MAP}.key"
		fi
}


# crypttab could be empty but must exists
if [ ! -f "/etc/crypttab" ]; then
	cryptlog "no crypttab found"
	exit 1
fi

load_params

VERBOSE="yes"
HASH="hash$$"

[ -x /usr/local/bin/wget ] || ln -s /usr/bin/wget /usr/local/bin/wget

# cannot do mount in /run/initramfs so stay in current dir
TMP="tmp$$"
TMP2="tmp2$$"
mkdir -p "$TMP" "$TMP2"

cryptlog "loading system crypttab"
while read MAP CRYPT KEY PARAM ; do
	MAP=$(echo "$MAP" | cut -d'#' -f1)
	# initramfs should include only crypt needing a password but we recheck it
	if [ "$KEY" = "none" -a "x$MAP" != "x#" -a "x$MAP" != "x" ]; then
		cryptlog "preparing $MAP $CRYPT"
		check=$(echo "$CRYPT" | grep '^/')
		if [ "x$check" != "x" ]; then
			CRYPT=$(echo "$CRYPT" | sed 's/\//__/g')
		fi
		echo "$MAP" > "$TMP/$CRYPT"
		crypttype=$(echo "$PARAM" | sed -r "s/.*($CRYPTYPES).*/\1/" | grep -E "($CRYPTYPES)")
		if [ "x$crypttype" = "x" ]; then
			crypttype="luks"
		fi
		echo "$MAP $crypttype" > "$TMP/$CRYPT"
	fi
done < "/etc/crypttab"

for device in ${TMP}/* ; do
	CRYPT=$(echo "$device" | cut -d'/' -f2)
	check=$(echo "$CRYPT" | grep '^_')
	if [ "x$check" != "x" ]; then
		CRYPT=$(echo "$CRYPT" | sed 's/__/\//g')
	fi
	MAP=$(cat "$device" | cut -d' ' -f1)
	CRYPTYPE=$(cat "$device" | cut -d' ' -f2)
	open_map
done

umount_devices

rm -rf "$TMP"
rm -d $TMP2/*
rm -d "$TMP2"
rm -f "$HASH" "$TMPCRYPTLOG" ${LOCALPREFIX}.*

[ -L /usr/local/bin/wget ] && rm /usr/local/bin/wget

cryptlog ""
cryptlog "created keys:"
for key in $(ls -1 genkey-*.key 2>/dev/null) ; do
	cryptlog "  $key"
done
cryptlog ""
exit 0

