#!/usr/bin/env bash
# Cycle to the next background for the current theme.
set -euo pipefail

OMARCHY_PATH="${OMARCHY_PATH:-$HOME/.local/share/omarchy}"
CURRENT="$HOME/.config/omarchy/current"

name="$(cat "$CURRENT/theme.name" 2>/dev/null || true)"
theme="$OMARCHY_PATH/themes/$name"
[ -d "$theme/backgrounds" ] || { echo "No backgrounds for theme '$name'" >&2; exit 1; }

mapfile -t backgrounds < <(find "$theme/backgrounds" -maxdepth 1 -type f -printf '%f\n' | sort)
total=${#backgrounds[@]}
[ "$total" -gt 0 ] || { echo "No backgrounds found" >&2; exit 1; }

cur="$(cat "$CURRENT/background.name" 2>/dev/null || true)"
idx=-1
for i in "${!backgrounds[@]}"; do
  [ "${backgrounds[$i]}" = "$cur" ] && { idx=$i; break; }
done
next=$(( (idx + 1) % total ))
printf '%s\n' "${backgrounds[$next]}" >"$CURRENT/background.name"

omarchy-theme-apply

pkill -x swaybg 2>/dev/null || true
sleep 0.1
setsid swaybg -i "$CURRENT/background" -m fill >/dev/null 2>&1 &
exit 0
