#!/usr/bin/env bash
set -e

# Cycles through the background images available for the current theme,
# then applies the pick via nomarchy-theme-bg-set (see the note at the end).

STATE_DIR="$HOME/.config/nomarchy"
STATE_FILE="$STATE_DIR/state.json"
mkdir -p "$STATE_DIR"
[[ ! -f $STATE_FILE ]] && echo "{}" > "$STATE_FILE"

THEME_NAME=$(jq -r '.theme // "summer-night"' "$STATE_FILE")

# Resolve themes directory (Built-in from Nix store via Home Manager, or user extra)
if [ -d "$HOME/.config/nomarchy/themes/$THEME_NAME" ]; then
  THEMES_DIR="$HOME/.config/nomarchy/themes"
else
  THEMES_DIR="$HOME/.local/share/nomarchy/themes"
fi

BG_DIR="$THEMES_DIR/$THEME_NAME/backgrounds"

if [ ! -d "$BG_DIR" ]; then
    notify-send "No background directory found for theme $THEME_NAME"
    exit 1
fi

mapfile -t BACKGROUNDS < <(ls "$BG_DIR" | sort)
TOTAL=${#BACKGROUNDS[@]}

if (( TOTAL == 0 )); then
    notify-send "No backgrounds found in $BG_DIR"
    exit 1
fi

CURRENT_BG=$(jq -r '.wallpaper' "$STATE_FILE")
INDEX=-1
for i in "${!BACKGROUNDS[@]}"; do
    if [[ "$BG_DIR/${BACKGROUNDS[$i]}" == "$CURRENT_BG" ]]; then
        INDEX=$i
        break
    fi
done

NEXT_INDEX=$(((INDEX + 1) % TOTAL))
NEW_BG="$BG_DIR/${BACKGROUNDS[$NEXT_INDEX]}"

# Apply through the shared setter: it persists state.json, updates the
# ~/.config/nomarchy/current/background symlink, and restarts swaybg — the
# single wallpaper daemon this distro actually runs. Previously this script
# drove swww directly, but it gated on `swww-daemon` (never running, since
# swaybg owns the wallpaper), so it spawned a second daemon competing with
# swaybg. swww was also renamed to awww and dropped its `init` subcommand in
# nixpkgs 26.05, so unifying on swaybg fixes both at once.
exec nomarchy-theme-bg-set "$NEW_BG"
