#!/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) || :

	# only 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
	fi
fi

# vi: ts=4 noexpandtab
