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

# "firstboot password" sounds so much better than "backdoor"

alias cmd_requires_luks_device=true
alias cmd_perform=cmd_add_secondary_password

function add_secondary_password {

    local luks_devices="$1"

    ##################################################################
    # Check whether we have already defined a firstboot password. If so,
    # refuse to do anything.
    # If we really wanted to be perfect, we could use luks_change_password
    # instead of luks_add_password in this case. But I'm lazy, not perfect.
    current_password=$(bootloader_get_fde_password)
    if [ -n "$current_password" ]; then
	display_errorbox "You have already defined a firstboot password"
	return 1
    fi

    ##################################################################
    # Generate a random firstboot password.
    insecure_password="$(fde_random_password)"

    # In order to install the new password, we need to prove to luks that
    # we're worthy. Either present a passfile or the recovery passphrase.
    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_add_password "$luks_dev" "$luks_keyfile" "$insecure_password"; then
            display_errorbox "Failed to add firstboot password to LUKS partition(${luks_dev})"
            return 1
        fi
    done

    rm -f "$luks_keyfile"

    # Write the firstboot password to the bootloader config.
    # We leave it to the caller to actually update the bootloader's
    # data in the EFI System Partition.
    if ! bootloader_set_fde_password "$insecure_password"; then
	display_errorbox "Failed to configure boot loader to use firstboot password"
	return 1
    fi
}

function cmd_add_secondary_password {

    if ! add_secondary_password "$1"; then
	return 1
    fi

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

    return 0
}
