#
#   Copyright (C) 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 Gary Lin <glin@suse.com>

. $SHAREDIR/commands/add-secondary-key
. $SHAREDIR/commands/tpm-enable

alias cmd_requires_luks_device=true
alias cmd_perform=cmd_regenerate_key

function cmd_regenerate_key {
    local luks_devices="$1"
    declare -A KEYSLOTS_OLD

    # Get the current keyslots for the TPM sealed key
    for luks_dev in ${luks_devices}; do
        KEYSLOTS_OLD["${luks_dev}"]=$(bootloader_get_keyslots ${luks_dev})
    done

    if ! enroll_tpm_secondary_key "${luks_devices}"; then
	return 1
    fi

    # Finish TPM key sealing
    tpm_enable "${luks_devices}"

    # Remove the previous keyslots
    for luks_dev in ${luks_devices}; do
        if [ -n "${KEYSLOTS_OLD[${luks_dev}]}" ]; then
            bootloader_remove_keyslots "${luks_dev}" "${KEYSLOTS_OLD[${luks_dev}]}"
            if [ "$?" -ne 0 ]; then
                display_errorbox "Failed to wipe out key slots in ${luks_dev}: ${KEYSLOTS_OLD[${luks_dev}]}"
                return 1
            fi
        fi
    done

    return 0
}
