#!/usr/bin/env bash

# Cycles through the background images available for the current theme.
# Declarative + Hybrid (instant swww) for Nomarchy NixOS.

STATE_DIR="$HOME/.config/home-manager"
THEME_STATE_FILE="$STATE_DIR/theme-state.nix"
WALLPAPER_STATE_FILE="$STATE_DIR/wallpaper-state.nix"

THEME_NAME=$(cat "$THEME_STATE_FILE" 2>/dev/null || echo "nord")

if [ -d "/etc/nixos/nomarchy/themes" ]; then
  THEMES_DIR="/etc/nixos/nomarchy/themes"
elif [ -d "/etc/nomarchy/themes" ]; then
  THEMES_DIR="/etc/nomarchy/themes"
else
  THEMES_DIR="/etc/nixos/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=$(cat "$WALLPAPER_STATE_FILE" 2>/dev/null)
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]}"

echo "$NEW_BG" > "$WALLPAPER_STATE_FILE"

# Instant feedback via swww
if pgrep -x swww-daemon >/dev/null; then
    swww img "$NEW_BG" --transition-type outer --transition-pos 0.85,0.97 --transition-step 90
else
    swww init && swww img "$NEW_BG"
fi

echo "Background set to $NEW_BG declaratively."
