#!/bin/bash
# udt-grub: rebuild the GRUB theme and say what root has to copy into /boot.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# Licensed under the GNU General Public License v2 only.
#
# Built, not installed: GRUB reads /boot before /home is mounted, so the theme
# is a root-owned copy of grub-theme-udt's dist/udt/, and this script only
# prints the command that refreshes it. Its background is a snapshot of the
# wallpaper and its colours come from the scheme, so both a wallpaper change
# and a scheme switch leave the copy stale.
#
# udt-accent starts this detached on every run; install.sh runs it in the
# foreground. The root steps go to the steps window through udt-steps, and
# the tab clears itself once /boot matches the build.

repo="$(dirname "$(readlink -f "$0")")/.."
grub_repo="$(realpath -m "$repo/../grub-theme-udt")"
[ -x "$grub_repo/build" ] || exit 0

# install.sh runs udt-accent, which starts this detached, and then runs this
# itself. build swaps dist/udt/ in with a rename, so two at once can collide.
mkdir -p "$grub_repo/dist"
exec 9>"$grub_repo/dist/.lock"
flock 9

"$grub_repo/build" >/dev/null || { echo "grub: its build failed, theme not refreshed" >&2; exit 1; }

theme=/boot/grub/themes/udt
copy="rm -rf $theme && cp -r \"$grub_repo/dist/udt\" /boot/grub/themes/"

steps() {
    if diff -rq "$grub_repo/dist/udt" "$theme" >/dev/null 2>&1; then
        return
    elif [ -d "$theme" ]; then
        echo "The GRUB theme was rebuilt. Refresh the copy in /boot as root:"
    else
        echo "The GRUB theme is built but not installed. As root:"
    fi
    echo "  $copy"
    grep -q "^GRUB_THEME=\"$theme/theme.txt\"" /etc/default/grub 2>/dev/null || {
        echo
        echo "Once, set GRUB_THEME=\"$theme/theme.txt\" in /etc/default/grub, then:"
        echo "  grub-mkconfig -o /boot/grub/grub.cfg"
    }
    # The panel title falls back to the OS name until one is set.
    [ -n "$("$repo/bin/udt-machine-name")" ] || {
        echo
        echo "Optional, the panel title:"
        echo "  \"$repo/bin/udt-machine-name\" \"My Machine\""
    }
}

out="$(steps)"
echo "grub theme: ${out:-up to date}"
# A theme that was never installed stays out of the steps window: a wallpaper
# change would otherwise keep asking for an install nobody wanted.
if [ -d "$theme" ] || [ -z "$out" ]; then
    printf '%s' "$out" | "$repo/bin/udt-steps" grub
fi
exit 0
