#!/bin/sh
# Halal Wallpapers: switch to the next wallpaper of your rotation.
# Run by the systemd user timer halalwallpapers-rotate.timer that the app creates when you turn rotation on.
# Offline by design: it only uses images already on this computer and never opens a network connection.
# It reads two files the app wrote (rotation/list: one slug per line, rotation/desktop: your desktop's name)
# and runs your desktop's own tool. Slugs are checked before they become paths; nothing is passed to a shell.
set -eu
APP="${XDG_DATA_HOME:-$HOME/.local/share}/com.halalwallpapers.HalalWallpapers"
R="$APP/rotation"
RUN="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
[ -s "$R/list" ] || exit 0
n=$(grep -c . "$R/list" || true)
[ "$n" -gt 0 ] || exit 0
i=$(cat "$R/index" 2>/dev/null || echo -1)
case "$i" in ''|*[!0-9-]*) i=-1 ;; esac
i=$(( (i + 1) % n ))
slug=$(sed -n "$((i + 1))p" "$R/list")
case "$slug" in ''|*[!a-z0-9-]*) echo "bad entry in rotation list" >&2; exit 1 ;; esac
f="$R/images/$slug.jpg"
[ -f "$f" ] || { echo "missing $f" >&2; exit 1; }
echo "$i" > "$R/index"
mkdir -p "$APP/wallpapers" && cp "$f" "$APP/wallpapers/current.jpg"
uri="file://$f"
mine() { pgrep -x -u "$(id -u)" "$1" >/dev/null 2>&1; }

case "$(cat "$R/desktop" 2>/dev/null)" in
  GNOME)
    gsettings set org.gnome.desktop.background picture-uri "$uri"
    gsettings set org.gnome.desktop.background picture-uri-dark "$uri" 2>/dev/null || true ;;
  Cinnamon) gsettings set org.cinnamon.desktop.background picture-uri "$uri" ;;
  MATE) gsettings set org.mate.background picture-filename "$f" ;;
  "KDE Plasma") plasma-apply-wallpaperimage "$f" ;;
  Xfce)
    props=$(xfconf-query -c xfce4-desktop -l | grep '/last-image$' || true)
    [ -n "$props" ] || props=/backdrop/screen0/monitor0/workspace0/last-image
    for p in $props; do xfconf-query -c xfce4-desktop -p "$p" -n -t string -s "$f"; done ;;
  LXQt) pcmanfm-qt --set-wallpaper="$f" --wallpaper-mode=zoom ;;
  Sway)
    SWAYSOCK=$(ls -t "$RUN"/sway-ipc.*.sock 2>/dev/null | head -n 1) swaymsg output '*' bg "$f" fill ;;
  Hyprland)
    # The instance signature changes at every login: use the newest running instance.
    HYPRLAND_INSTANCE_SIGNATURE=$(ls -t "$RUN/hypr" 2>/dev/null | head -n 1)
    export HYPRLAND_INSTANCE_SIGNATURE
    if mine hyprpaper; then
      hyprctl hyprpaper preload "$f" && hyprctl hyprpaper wallpaper ",$f"
    elif mine swww-daemon; then
      swww img "$f"
    elif mine swaybg; then
      # Started by Hyprland itself so it outlives this short-lived service; the old one stops once the new one is up.
      case "$f" in *"'"*) echo "unsupported path" >&2; exit 1 ;; esac
      old=$(pgrep -x -u "$(id -u)" swaybg)
      hyprctl dispatch exec "swaybg -o '*' -i '$f' -m fill" >/dev/null
      sleep 1
      for p in $old; do kill "$p" 2>/dev/null || true; done
    fi ;;
  *) echo "desktop not supported" >&2; exit 1 ;;
esac
