#!/bin/sh
# Reencrypt the root partition if necessary.

set -e

PREREQS=""
case $1 in
    prereqs) echo "${PREREQS}"; exit 0;;
esac

. /scripts/functions

msg() { [ -x /bin/plymouth ] && plymouth display-message --text="$@" || echo "$@"; }

[ -x /sbin/cryptsetup ] || return 0

DUMPFILE="/var/lib/reencrypt/dump"
DISABLEFILE="/etc/reencrypt-disabled"
PASSPHRASE="123456"

# if a file indicates we should do nothing, then just exit
[ -f "${rootmnt}${DISABLEFILE}" ] && exit 0

# if there's no luks dump to compare to, do nothing
[ -f "${rootmnt}${DUMPFILE}" ] || exit 0

# check whether rootfs is on a LUKS volume
if (cryptsetup status ${ROOT} >/dev/null 2>&1); then

	# find out the real device behind LUKS volume
	DEV=$(cryptsetup status ${ROOT} | awk -F: '$1~/device/ {gsub(/^[ \t]+/, "", $2); print $2}')

	# try to resume an interrupted reencryption
	(echo $PASSPHRASE | cryptsetup reencrypt --resume-only $DEV 2>/dev/null) || :

	# reencrypt if luksDump is the same as the one stored at image creation
	if (cryptsetup luksDump $DEV | cmp -s - "${rootmnt}${DUMPFILE}"); then
		msg "Encrypting the filesystem, please wait..."
		(echo $PASSPHRASE | cryptsetup reencrypt $DEV) && msg || msg "Encryption failed! Booting..."
	fi

	# trigger reencryption anytime the null cipher is being used
	if (cryptsetup luksDump $DEV | grep cipher_null); then
		msg
		plymouth hide-splash 2>/dev/null || :
		ttymode=$(stty -g) || :
		stty -echo -icanon min 0 time 0 || :

		PASSPHRASE=$(unl0kr -n -m "To ensure proper security, this device needs to be reencrypted. This may take about an hour.

Enter disk decryption passphrase again to proceed, or leave it empty to skip it until the next boot.
")

		stty "$ttymode" || :
		plymouth show-splash 2>/dev/null || :

		if [ "x$PASSPHRASE" != "x" ]; then
			msg "Encrypting the filesystem, please wait..."
			(echo $PASSPHRASE | cryptsetup reencrypt $DEV) && msg || msg "Encryption failed! Booting..."
		else
			msg "Encryption skipped. Booting..."
		fi
	fi
fi

# vi: ts=4 noexpandtab
