#!/bin/sh
# rikkiti-greeter-export — publish THIS user's accent + wallpaper to a system
# location the login greeter can read, so the greeter shows each user's own
# theme (their home dir is 0700, so the greeter — running as _greetd — can't
# read it directly). Run once at session start by rikkiti-session.
#
# Cache dir is /var/lib/rikkiti/greeter (created 1777, sticky like /tmp, by the
# installer) so any user's session can drop its own files without root.
set -eu

conf="${XDG_CONFIG_HOME:-$HOME/.config}/rikkiti/appearance.conf"
cache="/var/lib/rikkiti/greeter"
[ -d "$cache" ] || exit 0          # not installed → nothing to do
[ -f "$conf" ] || exit 0
u="$(id -un)"

val() { grep -E "^[[:space:]]*$1[[:space:]]*=" "$conf" 2>/dev/null | tail -1 | sed 's/^[^=]*=//; s/#.*//; s/^[[:space:]]*//; s/[[:space:]]*$//'; }

accent="$(val accent)"
dark="$(val dark)"
wall="$(val wallpaper)"

# Accent + dark → <user>.conf (world-readable).
tmp="$(mktemp "$cache/.$u.XXXXXX" 2>/dev/null)" || exit 0
{
	[ -n "$accent" ] && echo "accent = ${accent#\#}"
	[ -n "$dark" ]   && echo "dark = $dark"
} > "$tmp"
chmod 0644 "$tmp"
mv -f "$tmp" "$cache/$u.conf"

# Wallpaper: copy the image to a greeter-readable copy. If the value is a folder
# (per-display slideshow), pick the first image inside it.
img=""
if [ -n "$wall" ] && [ -f "$wall" ]; then
	img="$wall"
elif [ -n "$wall" ] && [ -d "$wall" ]; then
	img="$(find "$wall" -maxdepth 1 -type f \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' \) 2>/dev/null | sort | head -1)"
fi
if [ -n "$img" ] && [ -f "$img" ]; then
	tmpw="$(mktemp "$cache/.$u-wp.XXXXXX" 2>/dev/null)" || exit 0
	if cp -f "$img" "$tmpw" 2>/dev/null; then
		chmod 0644 "$tmpw"
		mv -f "$tmpw" "$cache/$u-wallpaper.${img##*.}"
		# Drop stale copies with a different extension.
		for e in png jpg jpeg webp; do
			[ "$e" = "${img##*.}" ] && continue
			rm -f "$cache/$u-wallpaper.$e" 2>/dev/null || true
		done
	else
		rm -f "$tmpw" 2>/dev/null || true
	fi
fi
exit 0
