#!/bin/sh
set -e

if [ -f /usr/lib/grub/grub-mkconfig_lib ]; then
  . /usr/lib/grub/grub-mkconfig_lib
else
  # no grub file, so we notify and exit gracefully
  echo "Cannot find grub config file, exiting." >&2
  exit 0
fi

# We can't cope with loop-mounted devices here.
case ${GRUB_DEVICE_BOOT} in
  /dev/loop/*|/dev/loop[0-9]) exit 0 ;;
esac

prepare_boot_cache="$(prepare_grub_to_access_device ${GRUB_DEVICE_BOOT} | sed -e "s/^/\t/")"

efi_vars_dir=/sys/firmware/efi/efivars

if test -e ${efi_vars_dir} ; then
  if test -e /boot/pcmemtestx64.efi && test -e /boot/grub/x86_64-efi ; then
    MEMTESTPATH=$( make_system_path_relative_to_its_root "/boot/pcmemtestx64.efi" )
    echo "Found pcmemtest 64bit EFI image: $MEMTESTPATH" >&2
    cat << EOF
menuentry "Memory test (pcmemtest)" {
EOF
    printf '%s\n' "${prepare_boot_cache}"
    cat << EOF
	linuxefi	$MEMTESTPATH
}
EOF
  elif test -e /boot/pcmemtestx32.efi && test -e /boot/grub/i386-efi ; then
    MEMTESTPATH=$( make_system_path_relative_to_its_root "/boot/pcmemtestx32.efi" )
    echo "Found pcmemtest 32bit EFI image: $MEMTESTPATH" >&2
    cat << EOF
menuentry "Memory test (pcmemtest)" {
EOF
    printf '%s\n' "${prepare_boot_cache}"
    cat << EOF
	linuxefi	$MEMTESTPATH
}
EOF
  fi
elif test -e /boot/pcmemtest.bin ; then
  MEMTESTPATH=$( make_system_path_relative_to_its_root "/boot/pcmemtest.bin" )
  echo "Found pcmemtest image: $MEMTESTPATH" >&2
  cat << EOF
menuentry "Memory test (pcmemtest)" {
EOF
  printf '%s\n' "${prepare_boot_cache}"
  cat << EOF
	linux	$MEMTESTPATH
}
EOF
fi

