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

# Initialize FDE_UEFI_BOOTDIR but do not overwrite it when someone
# sources this file a second time.
: ${FDE_UEFI_BOOTDIR:=""}

##################################################################
# Check if UEFI Secure Boot is enabled
##################################################################
function uefi_secure_boot_enabled {

    if ! [ -d /sys/firmware/efi ]; then
	fde_trace "This system does not seem to use UEFI. Full disk encryption with TPM protection not available"
	return 1
    fi

    if ! mokutil --sb-state 2> /dev/null | grep -q "enabled" ; then
	fde_trace "Secure Boot not enabled"
	return 1
    fi

    return 0
}

function uefi_set_loader {

    declare -g FDE_UEFI_BOOTDIR

    FDE_UEFI_BOOTDIR="$1"
}

function uefi_get_current_loader {

    entry=$(efibootmgr | grep BootCurrent|awk '{print $2;}')
    if [ -z "$entry" ]; then
	fde_trace "Cannot determine current UEFI boot entry"
	return 1
    fi

    file=$(efibootdump "Boot$entry" | sed 's/.*File(\([^)]*\)).*/\1/;t;d' | tr '\\' /)

    # Some boot setups do not use an EFI path with a file component.
    # Our ALP kvm images built with kiwi fall into that category.
    #
    # As a fallback, check if there is exactly one grub entry in /boot/efi,
    # and if so, use that.
    if [ -z "$file" -a -d "/boot/efi/EFI" ]; then
	set -- /boot/efi/EFI/*/grub.cfg
	if [ $# -eq 1 -a -f "$1" ]; then
		realpath $1
		return 0
	fi
    fi

    if [ -z "$file" ]; then
	fde_trace "Cannot determine loader path for UEFI boot entry $entry"
	return 1
    fi

    realpath "/boot/efi/$file"
}

function uefi_get_current_efidir {

    if [ -n "$FDE_UEFI_BOOTDIR" ]; then
	realpath "$FDE_UEFI_BOOTDIR"
	return 0
    fi

    loader=$(uefi_get_current_loader)
    if [ -n "$loader" ]; then
	dirname "$loader"
    fi
}
