#! /bin/bash

# Settings from /etc/sysconfig/filename are available as environment vars
# with the name 'SYS__FILENAME__KEY' (filename converted to upper case).
#
# Not all files are parsed, current list is:
#   bootloader, language
#

target=$(uname --hardware-platform)

if [ -z "$target" ] ; then
  echo "no target platform"
  exit 1
fi

case "$target" in
  i?86 ) target=i386 ;;
  x86_64 | amd64 ) target=x86_64 ;;
  aarch64 ) target=arm64 ;;
  arm* ) target=arm ;;
esac

target="$target-efi"

echo "target = $target"

# We install grub2 at the end of the installation, not within (bsc#979145)
if [ "$YAST_IS_RUNNING" = instsys ]; then
	echo "Skipping grub2-efi during installation. Will be done at the end"
	exit 0
fi

# EFI has 2 boot paths. The default is that there is a target file listed in
# the boot list. The boot list is stored in NVRAM and exposed as efivars.
#
# If no entry in the boot list was bootable (or a removable media is in the
# boot list), EFI falls back to removable media booting which loads a default
# file from /efi/boot/boot.efi.
#
# On U-Boot EFI capable systems we do not have NVRAM because we would have to
# store that on the same flash that Linux may be running on, creating device
# ownership conflicts. So on those systems we instead have to rely on the
# removable boot case.
#
# The easiest heuristic is that on "normal" EFI systems with working NVRAM,
# there is at least one efi variable visible. On systems without working NVRAM,
# we either see no efivars at all (booted via non-EFI entry point) or there is
# no efi variable exposed. Install grub in the removable location there.
append=
if [ ! -d /sys/firmware/efi/efivars -o ! "$(ls -A /sys/firmware/efi/efivars)" ]; then
	append="--no-nvram --removable"
fi

if [ "$SYS__BOOTLOADER__TRUSTED_BOOT" = yes -a -f "/usr/lib/grub2/$target/tpm.mod" ] ; then
	append="$append --suse-enable-tpm"
fi

if [ "$SYS__BOOTLOADER__SECURE_BOOT" = "yes" ] ; then
  if [ -x /usr/sbin/shim-install ] ; then
    ( set -x ; /usr/sbin/shim-install --config-file=/boot/grub2/grub.cfg $append )
  else
    echo "shim-install: command not found"
    exit 1
  fi
elif [ -x /usr/sbin/grub2-install ] ; then
  ( set -x ; /usr/sbin/grub2-install --target="$target" $append )
else
  echo "grub2-install: command not found"
  exit 1
fi
