#!/bin/bash
set -e

# GRUB's grub2_mkconfig script currently has some serious limitations, one of 
# them being not providing a way to modify anything done by previous scripts;
# unfortunately health_checker requires additional commands to be executed
# when selecting a boot entry (which is usually created by 10_linux), so as a
# horrible workaround the temporary output will be modified by a sed script.
#
# Will only work if output is redirected to a file (which should be the case
# in all automated cases), but not when the user is calling grub2-mkconfig by
# hand without redirection.

cfgfile="`readlink /proc/$$/fd/1`"
if [ -f "$cfgfile" ]; then
  lines_to_add='\n'
  lines_to_add+='\thealth_checker_flag=1\n'
  lines_to_add+='\tif [ "${env_block}" ] ; then\n'
  lines_to_add+='\t\tsave_env -f "${env_block}" health_checker_flag\n'
  lines_to_add+='\tfi'

  # The cp expression below will copy the new contents into the opened file;
  # the original process would not notice that and will continue writing from
  # the last position. To avoid that add the append flag to stdout to make sure
  # every write operation appends to the file.
  dd oflag=append count=0 status=none

  sed 's/^\(menuentry .*\)/\1'"${lines_to_add}"'/' "$cfgfile" > "$cfgfile".health_checker
  cp "$cfgfile".health_checker "$cfgfile"
  rm "$cfgfile".health_checker
fi

cat << EOF
# Prevent infinite waiting for disk if drivers in initrd are broken
extra_cmdline="\${extra_cmdline} rd.timeout=60 rd.retry=45"
EOF

