#! /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 | x86_64 ) target=i386-pc needs_installdevice=1 ;;
  ppc | ppc64* ) target=powerpc-ieee1275 needs_installdevice=1 ;;
  s390x ) target=s390x-emu ;;
esac

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 during installation. Will be done at the end"
	exit 0
fi

if [ "$target" = "powerpc-ieee1275" ] ; then
  grep -q PowerNV /proc/cpuinfo && exit 0
fi

if [ "$SYS__BOOTLOADER__TRUSTED_BOOT" = yes -a -d "/usr/lib/trustedgrub2/$target" ] ; then
  trusted="--directory=/usr/lib/trustedgrub2/$target"
fi

err=0
if [ -x /usr/sbin/grub2-install ] ; then
  if [ "$needs_installdevice" = 1 ] ; then
    if [ -r /etc/default/grub_installdevice ] ; then
      while read device ; do
        # ignore everything that doesn't look like a path
        [ "${device::1}" != "/" ] && continue
        if [ -b "$device" -o -f "$device" ] ; then
          ( set -x ; /usr/sbin/grub2-install $trusted --target="$target" --force --skip-fs-probe "$device" ) || err=1
        else
          echo "$device: not a block device"
          err=1
        fi
      done </etc/default/grub_installdevice
    else
      echo "/etc/default/grub_installdevice: permission denied"
      err=1
    fi
  else
    ( set -x ; /usr/sbin/grub2-install $trusted --target="$target" )
  fi
else
  echo "grub2-install: command not found"
  err=1
fi

exit $err

