#
#   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_tpm_disable

function tpm_disable {
    local luks_devices="$1"

    # Request the user to type the recovery password to prove the password is
    # correctly memorized, so that the user won't lock herself/himself out of
    # the system after reboot.
    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"
	    return 1
	fi
    done

    rm -f "$luks_keyfile"

    # Update the bootloader settings without TPM
    bootloader_enable_fde_without_tpm

    bootloader_remove_sealed_key

    return $?
}

function cmd_tpm_disable {
    if ! tpm_disable "$1"; then
	return 1
    fi

    return 0
}
