set timeout=10

# set default values for kernel, initramfs
# Other files can still override this
set kernel=/boot/vmlinuz
set initramfs=/boot/initrd

# Load custom env file
set env_file="/grubenv"
search --no-floppy --file --set=env_blk "${env_file}"

# Load custom env file
set oem_env_file="/grub_oem_env"
search --no-floppy --file --set=oem_blk "${oem_env_file}"

# Load custom config file
set custom_menu="/grubmenu"
search --no-floppy --file --set=menu_blk "${custom_menu}"

# Load custom config file
set custom="/grubcustom"
search --no-floppy --file --set=custom_blk "${custom}"

if [ "${oem_blk}" ] ; then
  load_env -f "(${oem_blk})${oem_env_file}"
fi

if [ "${env_blk}" ] ; then
  load_env -f "(${env_blk})${env_file}"
fi

# Save default
if [ "${next_entry}" ]; then
  set default="${next_entry}"
  set selected_entry="${next_entry}"
  set next_entry=
  save_env -f "(${env_blk})${env_file}" next_entry
else
  set default="${saved_entry}"
fi

## Display a default menu entry if set
if [ "${default_menu_entry}" ]; then
  set display_name="${default_menu_entry}"
else
  set display_name="Kairos"
fi

## Set a default fallback if set
if [ "${default_fallback}" ]; then
  set fallback="${default_fallback}"
else
  set fallback="0 1 2"
fi

insmod all_video
insmod loopback
insmod squash4
insmod serial

loadfont unicode
if [ "${grub_platform}" = "efi" ]; then
    ## workaround for grub2-efi bug: https://bugs.launchpad.net/ubuntu/+source/grub2/+bug/1851311
    rmmod tpm
fi

menuentry "${display_name}" --id cos {
  search --no-floppy --label --set=root COS_STATE
  set img=/cOS/active.img
  set label=COS_ACTIVE
  loopback loop0 /$img
  set root=($root)
  source (loop0)/etc/cos/bootargs.cfg
  linux (loop0)$kernel $kernelcmd ${extra_cmdline} ${extra_active_cmdline}
  initrd (loop0)$initramfs
}

menuentry "${display_name} (fallback)" --id fallback {
  search --no-floppy --label --set=root COS_STATE
  set img=/cOS/passive.img
  set label=COS_PASSIVE
  loopback loop0 /$img
  set root=($root)
  source (loop0)/etc/cos/bootargs.cfg
  linux (loop0)$kernel $kernelcmd ${extra_cmdline} ${extra_passive_cmdline}
  initrd (loop0)$initramfs
}

menuentry "${display_name} recovery" --id recovery {
  search --no-floppy --label --set=root COS_RECOVERY
  if [ test -s /cOS/recovery.squashfs ]; then
    set img=/cOS/recovery.squashfs
    set recoverylabel=COS_RECOVERY
  else
    set img=/cOS/recovery.img
  fi
  set label=COS_SYSTEM
  loopback loop0 /$img
  set root=($root)
  source (loop0)/etc/cos/bootargs.cfg
  linux (loop0)$kernel $kernelcmd ${extra_cmdline} ${extra_recovery_cmdline}
  initrd (loop0)$initramfs
}

if [ "${menu_blk}" ]; then
  source "(${menu_blk})${custom_menu}"
fi

if [ "${custom_blk}" ]; then
  source "(${custom_blk})${custom}"
fi
