#!/bin/bash
# Filename:      ${GRML_FAI_CONFIG}/config/scripts/GRMLBASE/45-grub-images
# Purpose:       create grub images for use in ISO
# Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2 or any later version.
################################################################################

set -e
set -u

TMP_CONFIG="/tmp/grub_config_efi"

# this allows us to find this specific Grml ISO,
# even if there are multiple Grml ISOs present
bootfile="${GRML_NAME}_$(TZ=UTC date +%s)"
echo "$bootfile" > "${target}/"boot/grub/bootfile.txt

cat > "${target}/${TMP_CONFIG}" <<EOF
search.file /conf/bootfile_$bootfile root
set prefix=(\$root)/boot/grub
insmod normal
normal
echo "E: Could not find root device (for /conf/bootfile_$bootfile)!"
EOF

ARCHS=(i386-pc)
declare -A ADDITIONAL_MODULES
ADDITIONAL_MODULES[i386-pc]="biosdisk"

# arm64 doesn't provide /usr/lib/grub/i386-efi, so we don't include
# i386-pc in $ARCHS (whereas on AMD64 we have both i386-pc + x86_64-efi)
if ifclass ARM64 ; then
  if [ -r "${target}"/usr/lib/grub/arm64-efi/moddep.lst ] ; then
    ARCHS=(arm64-efi)
    # NOTE: efi_uga (EFI Universal Graphics Adapter) is deprecated + unavailable on arm64
    ADDITIONAL_MODULES[arm64-efi]="efi_gop"  # no efi_uga available
  else
    echo "/usr/lib/grub/arm64-efi/moddep.lst.lst could not be found, skipping."
    echo "NOTE: grub-efi-arm64-bin not installed?"
  fi
fi

if ifclass AMD64 ; then
  if [ -r "${target}"/usr/lib/grub/x86_64-efi/moddep.lst ] ; then
    ARCHS+=(x86_64-efi)
    ADDITIONAL_MODULES[x86_64-efi]="efi_gop efi_uga"
  else
    echo "/usr/lib/grub/x86_64-efi/moddep.lst could not be found, skipping."
    echo "NOTE: grub-efi-amd64-bin not installed?"
  fi
fi

if ifclass I386 ; then
  if [ -r "${target}"/usr/lib/grub/i386-efi/moddep.lst ] ; then
    ARCHS+=(i386-efi)
    ADDITIONAL_MODULES[i386-efi]="efi_gop efi_uga"
  else
    echo "/usr/lib/grub/i386-efi/moddep.lst could not be found, skipping."
    echo "NOTE: grub-efi-ia32 not installed?"
  fi
fi

for arch in "${ARCHS[@]}" ; do
  filename=''
  case "$arch" in
    i386-pc)    filename=/boot/grub/grub.img ;;
    x86_64-efi) filename=/boot/bootx64.efi   ;;
    i386-efi)   filename=/boot/bootia32.efi  ;;
    arm64-efi)  filename=/boot/bootaa64.efi  ;;
  esac

  $ROOTCMD grub-mkimage -O $arch -o "$filename" --prefix=/boot/grub/ --config="$TMP_CONFIG" \
    echo iso9660 part_msdos search_fs_file test \
    fat ext2 reiserfs xfs btrfs squash4 part_gpt lvm \
    ${ADDITIONAL_MODULES[$arch]}
done

rm -f "${target}/${TMP_CONFIG}"
echo "Generated Grub images"

## END OF FILE #################################################################
# vim:ft=sh expandtab ai tw=80 tabstop=4 shiftwidth=2
