#!/usr/bin/env bash
# Set the background for the current theme to a given image path.
set -euo pipefail

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

[ -n "${1:-}" ] && [ -f "$1" ] || { echo "Usage: omarchy-theme-bg-set <path-to-image>" >&2; exit 1; }
bg="$(realpath "$1")"
name="$(cat "$CURRENT/theme.name" 2>/dev/null || true)"

if [ -n "$name" ] && [ "$(dirname "$bg")" = "$OMARCHY_PATH/themes/$name/backgrounds" ]; then
  basename "$bg" >"$CURRENT/background.name"
  ln -sfn "$bg" "$CURRENT/background"
else
  rm -f "$CURRENT/background.name"
  ln -sfn "$bg" "$CURRENT/background"
fi

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