#!/usr/bin/env bash
# Re-skin Hyprland: pick a random wallpaper, crossfade to it, regenerate the
# colorscheme with wallust. Safe to run from a systemd timer.
set -euo pipefail

WALLPAPER_DIR="${WALLPAPER_DIR:-$HOME/photo/wallpapers}"
STATE_FILE="${XDG_RUNTIME_DIR:-/tmp}/hypr_refresh.last"

# If the wallpaper daemon isn't up we're almost certainly not in a graphical
# session (or hyprland hasn't started it yet). Nothing to do -- bail quietly so
# the timer doesn't spam failures.
if ! awww query >/dev/null 2>&1; then
    echo "awww-daemon not running; skipping refresh" >&2
    exit 0
fi

# Collect wallpapers null-delimited so paths with spaces are safe.
# Debian/Ubuntu ship fd as fdfind; Arch ships it as fd.
FD=$(command -v fd || command -v fdfind) || { echo "neither fd nor fdfind found" >&2; exit 1; }
mapfile -d '' -t wallpapers < <("$FD" -0 -e jpg -e jpeg -e png . "$WALLPAPER_DIR")
if ((${#wallpapers[@]} == 0)); then
    echo "No wallpapers found in $WALLPAPER_DIR" >&2
    exit 1
fi

# Avoid showing the same wallpaper twice in a row.
last=$(cat "$STATE_FILE" 2>/dev/null || true)
if ((${#wallpapers[@]} > 1)) && [[ -n $last ]]; then
    filtered=()
    for w in "${wallpapers[@]}"; do
        [[ $w != "$last" ]] && filtered+=("$w")
    done
    wallpapers=("${filtered[@]}")
fi

background=$(shuf -n1 -e "${wallpapers[@]}")
echo "Setting background to: $background"
printf '%s\n' "$background" >"$STATE_FILE"

awww img "$background" \
    --transition-type random \
    --transition-fps 60 \
    --transition-duration 2.5

wallust -q run -s "$background"
for s in /tmp/kitty-*; do
    kitten @ --to "unix:$s" set-colors --all --configured \
        "${XDG_CACHE_HOME:-$HOME/.cache}/wallust/colors-kitty.conf" 2>/dev/null || true
done
