#
#   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 {
    luks_dev="$1"
    declare -A EXTRA_KEYSLOTS_OLD

    # Get the current keyslots for the TPM sealed key
    KEYSLOTS_OLD=$(bootloader_get_keyslots ${luks_dev})

    # Get the current keyslots in the extra devices
    for extra_dev in ${FDE_EXTRA_DEVS}; do
        EXTRA_KEYSLOTS_OLD["${extra_dev}"]=$(bootloader_get_keyslots ${extra_dev})
    done

    enroll_tpm_secondary_key "${luks_dev}"

    # Finish TPM key sealing
    tpm_enable ${luks_dev}

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

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

    return 0
}
