#!/bin/sh
# lightdm-greeter-wallpaper — mirror the user's desktop wallpaper to the greeter.
#
# The wallpaper picker (~/.config/scripts/wallpaper-picker) writes the chosen
# per-monitor wallpapers to ~/.config/hypr/usr/wallpaper.conf. This helper copies
# the wallpaper of the greeter's main monitor to a world-readable system path so
# the LightDM greeter — which runs as the unprivileged 'lightdm' user and cannot
# read a 0700 home — can use it as its background.
#
# Run as root (it needs to read the user's home) via lightdm-greeter-wallpaper.path,
# which fires whenever wallpaper.conf changes. Usage:
#     lightdm-greeter-wallpaper <username>
#
# Monitor choice: prefer $PREFERRED_MONITOR (the main/4K panel that hosts the
# login form); fall back to the first wallpaper entry. Set PREFERRED_MONITOR in
# the environment (the .service does) to match your primary output.

set -eu

USER_NAME="${1:?usage: lightdm-greeter-wallpaper <username>}"
PREFERRED="${PREFERRED_MONITOR:-}"
DEST="/usr/share/backgrounds/lightdm-greeter-bg.png"

HOME_DIR="$(getent passwd "$USER_NAME" | cut -d: -f6)"
[ -n "$HOME_DIR" ] || { echo "no home for $USER_NAME" >&2; exit 0; }
STATE="$HOME_DIR/.config/hypr/usr/wallpaper.conf"
[ -r "$STATE" ] || { echo "no wallpaper state at $STATE" >&2; exit 0; }

# Path for the preferred monitor, else the first wallpaper path in the file.
src=""
if [ -n "$PREFERRED" ]; then
    src="$(awk -v m="$PREFERRED" '
        $1=="monitor" && $3==m { want=1; next }
        want && $1=="path"     { print $3; exit }' "$STATE")"
fi
[ -n "$src" ] || src="$(awk '$1=="path"{print $3; exit}' "$STATE")"

[ -n "$src" ] && [ -r "$src" ] || { echo "no readable wallpaper resolved" >&2; exit 0; }

install -Dm644 "$src" "$DEST"
echo "greeter background <- $src"
