#!/bin/sh
# Enable 'splash' only on UEFI desktop installs, and only if Plymouth is present.
# Runs before 10update-initramfs, so we only call update-grub here.
#

# Run only on UEFI installs
[ -d /sys/firmware/efi ] || exit 0

# Require plymouth in the target system (otherwise splash is pointless)
in-target dpkg -s plymouth >/dev/null 2>&1 || exit 0

# Heuristic “desktop present?” check — avoid debconf; rely on packages/DM.
if ! in-target sh -c '
  dpkg -s trisquel-desktop-common >/dev/null 2>&1 ||
  dpkg -s triskel                 >/dev/null 2>&1 ||
  dpkg -s trisquel-gnome          >/dev/null 2>&1 ||
  dpkg -s trisquel-mini           >/dev/null 2>&1 ||
  dpkg -s lightdm                 >/dev/null 2>&1 ||
  dpkg -s gdm3                    >/dev/null 2>&1 ||
  dpkg -s sddm                    >/dev/null 2>&1
'; then
# No desktop, then do nothing
  exit 0
fi

CFG=/target/etc/default/grub
[ -f "$CFG" ] || exit 0

# If the key is missing entirely, create it with just "splash"
grep -q '^GRUB_CMDLINE_LINUX_DEFAULT=' "$CFG" \
  || echo 'GRUB_CMDLINE_LINUX_DEFAULT="splash"' >> "$CFG"

# Normalize trivial cases:
#    - empty quotes > "splash"
#    - unquoted value > quote it
sed -i -r \
  -e 's/^GRUB_CMDLINE_LINUX_DEFAULT=""$/GRUB_CMDLINE_LINUX_DEFAULT="splash"/' \
  -e 's/^(GRUB_CMDLINE_LINUX_DEFAULT)=([^"].*)$/\1="\2"/' \
  "$CFG"

# If 'splash' is already present, leave as-is; otherwise append it
grep -q '^GRUB_CMDLINE_LINUX_DEFAULT=.*\bsplash\b' "$CFG" || \
  sed -i -r 's/^(GRUB_CMDLINE_LINUX_DEFAULT="[^"]*)"/\1 splash"/' "$CFG"

# Regenerate grub.cfg; never fail finish-install
in-target update-grub >/dev/null 2>&1 || true

# Always succeed so remaining finish-install hooks run
exit 0
