#!/usr/bin/env bash
# Set the active Omarchy theme (name or "<theme>" from the menu).
set -euo pipefail

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

if [ -z "${1:-}" ]; then
  echo "Usage: omarchy-theme-set <theme-name>" >&2
  exit 1
fi

# Normalise: strip markup, lowercase, spaces -> dashes
name="$(printf '%s' "$1" | sed -E 's/<[^>]+>//g' | tr '[:upper:]' '[:lower:]' | tr ' ' '-')"

if [ ! -d "$OMARCHY_PATH/themes/$name" ]; then
  echo "Theme '$name' does not exist" >&2
  exit 1
fi

printf '%s\n' "$name" >"$CURRENT/theme.name"
# Start each theme on its first background
find "$OMARCHY_PATH/themes/$name/backgrounds" -maxdepth 1 -type f -printf '%f\n' | sort | head -n1 \
  >"$CURRENT/background.name"

omarchy-theme-apply

# Restart clients so the new colours/wallpaper take effect
pkill -x swaybg 2>/dev/null || true
sleep 0.1
setsid swaybg -i "$CURRENT/background" -m fill >/dev/null 2>&1 &
pkill -SIGUSR2 waybar 2>/dev/null || true
hyprctl reload >/dev/null 2>&1 || true

command -v notify-send >/dev/null && notify-send -u low "Theme: $name" || true
exit 0
