#!/bin/sh

## Copyright (C) 2019 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

#set -x

true "grub-live $0: START"

set -e
set -o allexport

pkg_installed() {
   ## Cannot use '&>' because it is a bashism.
   if dpkg-query --show --showformat='${db:Status-Status}\n' "$1" 2>/dev/null | grep --quiet --fixed-strings -e 'installed' -e 'pending' ; then
      return 0
   fi
   return 1
}

GRUB_DEVICE="/dev/disk/by-uuid/${GRUB_DEVICE_UUID}"
unset GRUB_DEVICE_UUID

GRUB_DISTRIBUTOR="LIVE mode USER (For daily activities.)"
GRUB_DISABLE_RECOVERY="true"

if pkg_installed initramfs-tools ; then
   true "grub-live $0: INFO: initramfs-tools detected."
   ## https://forums.whonix.org/t/bullseye-live-boot-needs-grub-disable-linux-uuid-true-parameter-in-etc-grub-d-11-linux-live/9066
   ## https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=994138
   ## https://askubuntu.com/a/283320
   GRUB_DISABLE_LINUX_UUID="true"

   GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX boot=live plainroot union=overlay ip=frommedia noeject nopersistence"
elif pkg_installed dracut ; then
   true "grub-live $0: INFO: dracut detected."
   if ! test -x /usr/lib/dracut/modules.d/90overlay-root/overlay-mount.sh ; then
      echo "\
grub-live $0: ERROR: It has been detected that this system is using dracut but but file /usr/lib/dracut/modules.d/90overlay-root/overlay-mount.sh is not executable. This means that no live mode boot menu entry will be added.
" >&2
      exit 0
   fi

   ## https://www.kicksecure.com/wiki/Grub-live#Developer_Information

   ## using Debian forked upstream module 90overlay-root
   ## works on Debian bookworm
   ## TODO: disable this on Debian trixie
   GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX rootovl"

   ## using dracut upstream module 90overlayfs
   ## TODO: use this on Debian trixie
   ## NOTE: overlayfs module needed
   #GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX rd.live.overlay.overlayfs=1 "

   ## Unnecessary! It's for systems where you have an immutable base filesystem and a persistent overlay,
   ## and you want to make the overlay read-only, putting another overlay on top of it.
   #GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX rd.live.overlay.readonly=1 "
else
   echo "\
grub-live $0: ERROR: Neither initramfs-tools nor dracut is installed. Support for other initrd generators is not implemented. This means that no live mode boot menu entry will be added.
" >&2
   exit 0
fi

if test -x /etc/grub.d/10_linux ; then
	/etc/grub.d/10_linux
fi

true "grub-live $0: END"
