#! /bin/sh
set -e

# older versions of grub2 do not have this yet (LP: #459080)
if [ ! -e /usr/share/grub/grub-mkconfig_lib ]; then
    echo "no grub-mkconfig_lib, exiting"
    exit 0
fi

. /usr/share/grub/grub-mkconfig_lib

if [ "${grub_platform}" != "efi" ]; then
	MEMTESTSFX="bin"
else
	MEMTESTSFX="efi"
fi

if [ -e /boot/memtest.bin ]; then
	MEMTESTPATH=$( make_system_path_relative_to_its_root "/boot/memtest.bin" )
	echo "Found memtest86+ image: $MEMTESTPATH" >&2
	cat <<- EOF
	if [ "\${grub_platform}" != "efi" ]; then
	menuentry "Memory test (memtest86+)" {
	EOF
	prepare_grub_to_access_device "${GRUB_DEVICE_BOOT}" | sed -e "s/^/\t/"
	cat <<- EOF
		linux $MEMTESTPATH
	}
	menuentry "Memory test (memtest86+, serial console 115200)" {
	EOF
	prepare_grub_to_access_device "${GRUB_DEVICE_BOOT}" | sed -e "s/^/\t/"
	cat <<- EOF
		linux $MEMTESTPATH console=ttyS0,115200n8
	}
	fi
	EOF
fi
if [ -e /boot/memtest.efi ]; then
	MEMTESTPATH=$( make_system_path_relative_to_its_root "/boot/memtest.efi" )
	echo "Found memtest86+ image: $MEMTESTPATH" >&2
	cat <<- EOF
	if [ "\${grub_platform}" = "efi" ]; then
	menuentry "Memory test (memtest86+)" {
	EOF
	prepare_grub_to_access_device "${GRUB_DEVICE_BOOT}" | sed -e "s/^/\t/"
	cat <<- EOF
		linux $MEMTESTPATH
	}
	menuentry "Memory test (memtest86+, serial console 115200)" {
	EOF
	prepare_grub_to_access_device "${GRUB_DEVICE_BOOT}" | sed -e "s/^/\t/"
	cat <<- EOF
		linux $MEMTESTPATH console=ttyS0,115200n8
	}
	fi
	EOF
fi
