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

function remove_secondary_password {

    local luks_devices="$1"

    ##################################################################
    # Check if we have stashed a key under the doormat
    ##################################################################
    insecure_password=$(bootloader_get_fde_password)
    if [ -z "$insecure_password" ]; then
	if [ "$2" = "--verbose" ]; then
	    display_infobox "No firstboot password configured"
	fi
	return 0
    fi

    ##################################################################
    # Nuke the LUKS header slot associated with this password
    ##################################################################
    luks_keyfile=$(luks_write_password pass "${insecure_password}")
    for luks_dev in ${luks_devices}; do
	if ! luks_drop_key "$luks_dev" "$luks_keyfile"; then
	    display_errorbox "Unable to disable firstboot password(${luks_dev})"
	    return 1
	fi
    done

    ##################################################################
    # And finally, wipe the password from the boot loader config files.
    ##################################################################
    if ! bootloader_set_fde_password ""; then
	display_errorbox "Failed to disable firstboot password in boot loader"
	return 1
    fi
}

function cmd_remove_secondary_password {

    if ! remove_secondary_password "$1" --verbose; then
	return 1
    fi

    if ! bootloader_commit_config; then
	display_errorbox "Failed to update bootloader configuration"
	return 1
    fi

    return 0
}
