#!/bin/sh

exec < /dev/console >/dev/console 2>&1
type getarg > /dev/null 2>&1 || . /lib/dracut-lib.sh

# get systemd credential
# https://systemd.io/CREDENTIALS/
get_credential()
{
	local var="${1:?}"
	local name="${2:?}"
	[ -n "$CREDENTIALS_DIRECTORY" ] || return 1
	[ -e "$CREDENTIALS_DIRECTORY/$name" ] || return 1
	read -r "$var" < "$CREDENTIALS_DIRECTORY/$name" || [ -n "${!var}" ]
}

encrypt=
if get_credential encrypt rd.encrypt && [ "$encrypt" = "no" ]; then
	exit 0
fi

# check whether encryption was explicitly turned off
if ! getargbool 1 rd.encrypt; then
	exit 0
fi

# XXX: this is so dirty
systemctl start sysroot.mount
mount --target-prefix /sysroot --fstab /sysroot/etc/fstab /var
if [ ! -e /sysroot/var/lib/YaST2/reconfig_system ]; then
	echo "system already configured, no encryption"
	umount /sysroot/var
	exit 0
fi
umount /sysroot/var

# silence systemd
kill -SIGRTMIN+21 1
echo -ne '\n\n\a'
read -n1 -s -r -t 10 -p "*** Press ESC to prevent encrypting the disk" inhibitor
echo
if [ "$inhibitor" != $'\e' ]; then
	/usr/bin/disk-encryption-tool -v --gen-key || die "Encryption failed"
fi
# turn messages on again
kill -SIGRTMIN+20 1
