#
#   Copyright (C) 2022, 2023 SUSE LLC
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   Written by Olaf Kirch <okir@suse.com>

alias cmd_requires_luks_device=true
alias cmd_perform=cmd_change_password

function cmd_change_password {

    local luks_devices="$1"

    luks_keyfile=$(fde_make_tempfile pass.key)
    if ! fde_request_recovery_passfile "$luks_keyfile"; then
	display_errorbox "Unable to obtain recovery password; aborting."
	return 1
    fi

    for luks_dev in ${luks_devices}; do
	if ! luks_verify_password "$luks_dev" "$luks_keyfile"; then
	    rm -f "$luks_keyfile"
	    display_errorbox "Failed to verify password on LUKS partition(${luks_dev})"
	    return 1
	fi
    done

    request_new_password "Please enter new LUKS recovery password"
    if [ -z "$result_password" ]; then
        display_errorbox "Unable to obtain new recovery password"
	return 1
    fi
    luks_new_keyfile=$(luks_write_password newpass "${result_password}")

    for luks_dev in ${luks_devices}; do
	if ! luks_set_password "$luks_dev" "$luks_keyfile" "$luks_new_keyfile"; then
	    display_errorbox "Failed to change LUKS recovery password(${luks_dev})"
	    rm -f "$luks_keyfile" "$luks_new_keyfile"
	    return 1
	fi
    done

    rm -f "$luks_keyfile" "$luks_new_keyfile"
}
