#!/bin/bash

# Cycles through the background images available

BACKGROUNDS_DIR="$HOME/.config/omarchy/current/backgrounds/"
CURRENT_BACKGROUND_LINK="$HOME/.config/omarchy/current/background"

mapfile -d '' -t BACKGROUNDS < <(find "$BACKGROUNDS_DIR" -type f -print0 | sort -z)
TOTAL=${#BACKGROUNDS[@]}

# Get current background from symlink
if [[ -L "$CURRENT_BACKGROUND_LINK" ]]; then
  CURRENT_BACKGROUND=$(readlink "$CURRENT_BACKGROUND_LINK")
else
  # Default to first background if no symlink exists
  CURRENT_BACKGROUND="${BACKGROUNDS[0]}"
fi

# Find current background index
INDEX=0
for i in "${!BACKGROUNDS[@]}"; do
  if [[ "${BACKGROUNDS[$i]}" == "$CURRENT_BACKGROUND" ]]; then
    INDEX=$i
    break
  fi
done

# Get next background (wrap around)
NEXT_INDEX=$(((INDEX + 1) % TOTAL))
NEW_BACKGROUND="${BACKGROUNDS[$NEXT_INDEX]}"

# Set new background symlink
ln -nsf "$NEW_BACKGROUND" "$CURRENT_BACKGROUND_LINK"

# Relaunch swaybg
pkill -x swaybg
setsid swaybg -i "$NEW_BACKGROUND" -m fill >/dev/null 2>&2 &
