cat <<EOF
# SEAPATH boot count

# Note: new_entry_id and safe_entry_id come from 10_linux

# Grub always labels booting drive "hd0". The device map generated by grub-mkdevicemap may be wrong.
# As a workaround, always use "hd0" for disk (partition is still automatically found)
bootcountenv="$(grub-probe /boot/efi/bootcountenv -t drive | sed -e 's/(.*,\(.*\))/(hd0,\1)/')$(grub-mkrelpath /boot/efi/bootcountenv)"

# Allow using bootcount&recovery on a single kernel (to catch userland crash)
if [ -z "\$safe_entry_id"]; then
  safe_entry_id="\$new_entry_id"
fi

if [ ( -s \$bootcountenv ) -a ( -n "\$new_entry_id" ) -a ( "\$safe_entry_id" )]; then
  set seapath_boot_count_params="seapath.bootcount_action=nothing"
  set bootcount="disabled"
  set newbootcount="disabled"
  load_env -f \$bootcountenv bootcount
  set newbootcount="\${bootcount}"
  echo "Read bootcount = \"\$bootcount\""
  if [ \$bootcount == "0" ]; then
    set default="\${new_entry_id}"
    set newbootcount=1
  elif [ \$bootcount == "1" ]; then
    set default="\${new_entry_id}"
    set newbootcount=2
  elif [ \$bootcount == "2" ]; then
    set default="\${new_entry_id}"
    set newbootcount=3
  elif [ \$bootcount == "3" ]; then
    echo "Reached maximum failed boot count, starting recovery..."
    set default="\${safe_entry_id}"
    set seapath_boot_count_params="seapath.bootcount_action=recovery"
    export seapath_boot_count_params
    set newbootcount=3
  else
    echo "Seapath boot count disabled"
    # for every other case, don't change default
  fi

  echo "Seapath boot count: Grub default is \"\${default}\""

  if [ "\$newbootcount" != "\$bootcount" ]; then
    set bootcount=\$newbootcount
    save_env -f \$bootcountenv bootcount bootcount_action
    echo "Written bootcount = \$bootcount"
  fi
else
  echo "Warning: Seapath boot count env file \"\$bootcountenv\" not found or new/safe kernel entry missing: Boot count disabled"
fi
sleep 1 # Allow to see the message on the console before it is redrawn by the menu
EOF
