#! /bin/sh
set -e

. /usr/lib/grub/grub-mkconfig_lib

have_lkrn=0
have_efi=0

# iPXE is only supported on the following architectures
case $(dpkg --print-architecture) in
  *i386) have_lkrn=1; have_efi=0 ;;
  *amd64) have_lkrn=1; have_efi=1 ;;
  *arm64) have_lkrn=0; have_efi=1 ;;
  *riscv64) have_lkrn=0; have_efi=1 ;;
  *loong64) have_lkrn=0; have_efi=1 ;;
  *) exit 0 ;;
esac

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

if [ $have_lkrn -eq 1 ]; then
  IPXE=/boot/ipxe.lkrn
elif [ $have_efi -eq 1 ]; then
  IPXE=/boot/ipxe.efi
fi
if test -e "$IPXE" ; then
  IPXEPATH=$( make_system_path_relative_to_its_root "$IPXE" )
  # Remove the extension
  IPXEPATH=${IPXEPATH%.*}
  echo "Found iPXE image: $IPXE" >&2
  cat << EOF
menuentry "Network boot (iPXE)" --users "" --class network --id ipxe {
${prepare_boot_cache}
EOF
  save_default_entry | grub_add_tab
  if [ $have_efi -eq 1 ] && [ $have_lkrn -eq 1 ]; then
	echo 'if [ "$grub_platform" = "efi" ]; then'
  fi
  if [ $have_efi -eq 1 ]; then
    echo "chainloader $IPXEPATH.efi"
  fi;
  if [ $have_efi -eq 1 ] && [ $have_lkrn -eq 1 ]; then
	echo 'else'
  fi
  if [ $have_lkrn -eq 1 ]; then
    cat <<EOF
      linux16 $IPXEPATH.lkrn
      # If the user provided an iPXE script, load it
      if [ -f $IPXEPATH.ipxe ]; then
        initrd16 $IPXEPATH.ipxe
      fi
EOF
  fi
  if [ $have_efi -eq 1 ] && [ $have_lkrn -eq 1 ]; then
	echo 'fi'
  fi
  echo "}"
fi
