#!/bin/sh

alterator_api_version=1

. alterator-sh-functions

CRYPTSETUP_KEY=/tmp/empty
[ -e "$CRYPTSETUP_KEY" ] || :> "$CRYPTSETUP_KEY"

luks_chpasswd()
{
	local errmsg=
	for UUID in $(blkid -o value -s UUID | sort -u);
	do
		device=$(blkid -U "$UUID")
		[ "$(blkid -o value -s TYPE "$device")" = "crypto_LUKS" ] || continue
		cryptsetup isLuks "$device" || continue
		# filter devices with passwords set
		echo "" | cryptsetup luksOpen --test-passphrase "$device" || continue
		errmsg="$(echo "$1" | cryptsetup --force-password --key-file "$CRYPTSETUP_KEY" --pbkdf pbkdf2 luksChangeKey "$device" 2>&1)" ||
			write_error "`_ "Failed setup the password:"` $errmsg"
	done
}

change_password()
{
	if test_bool "$in_auto" && [ -z "$in_passwd_auto" ]; then
		write_error "`_ "You should define a password for LUKS device"`"
	elif test_bool "$in_auto" && [ -n "$in_passwd_auto" ]; then
		luks_chpasswd "$in_passwd_auto"
	elif [ -z "$in_passwd_1" -a -z "$in_passwd_2" ]; then
		write_error "`_ "You should define a password for LUKS device"`"
	elif [ "$in_passwd_1" != "$in_passwd_2" ]; then
		write_error "`_ "Passwords mismatch"`"
	else
		luks_chpasswd "$in_passwd_1"
	fi
}

generate_password()
{
	write_string_param passwd_auto "$(pwqgen)"
}

have_active_luks_device()
{
	[ -n "$(find /dev/mapper/ -maxdepth 1 -name '*luks')" ] && write_bool_param luks 1 || write_bool_param luks 0
}

alterator_export_proc change_password
alterator_export_proc generate_password
alterator_export_proc have_active_luks_device

message_loop
