#!/bin/sh -e

# omarchy-theme-set: Set a theme, specified by its name.
# Usage: omarchy-theme-set <theme-name>

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

THEMES_DIR="$HOME/.local/share/themes"
CURRENT_THEME_DIR="${THEMES_DIR}/current/theme"

THEME_NAME=$(echo "$1" | sed -E 's/<[^>]+>//g' | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
THEME_PATH="$THEMES_DIR/available/$THEME_NAME"

base_theme_dir=$(dirname "$CURRENT_THEME_DIR")
if [[  !  -d "$base_theme_dir" ]]; then
    mkdir -p $base_theme_dir
fi

# Check if the theme entered exists
if [[ ! -d "$THEME_PATH" ]]; then
  echo "Theme '$THEME_NAME' does not exist in $THEMES_DIR" >&2
  exit 2
fi

# Update theme symlinks
ln -nsf "$THEME_PATH" "$CURRENT_THEME_DIR"

# Change gnome modes
if [[ -f "$CURRENT_THEME_DIR/light.mode" ]]; then
  gsettings set org.gnome.desktop.interface color-scheme "prefer-light"
  gsettings set org.gnome.desktop.interface gtk-theme "Adwaita"
else
  gsettings set org.gnome.desktop.interface color-scheme "prefer-dark"
  gsettings set org.gnome.desktop.interface gtk-theme "Adwaita-dark"
fi

# Change gnome icon theme color
if [[ -f "$CURRENT_THEME_DIR/icons.theme" ]]; then
  gsettings set org.gnome.desktop.interface icon-theme "$(<$CURRENT_THEME_DIR/icons.theme)"
else
  gsettings set org.gnome.desktop.interface icon-theme "Yaru-blue"
fi

# Change Chromium colors
if command -v chromium &>/dev/null; then
  if [[ -f "$CURRENT_THEME_DIR/light.mode" ]]; then
    chromium --no-startup-window --set-color-scheme="light"
  else
    chromium --no-startup-window --set-color-scheme="dark"
  fi

  if [[ -f "$CURRENT_THEME_DIR/chromium.theme" ]]; then
    chromium --no-startup-window --set-theme-color="$(<$CURRENT_THEME_DIR/chromium.theme)"
  else
    # Use a default, neutral grey if theme doesn't have a color
    chromium --no-startup-window --set-theme-color="28,32,39"
  fi
fi

if [[ ! -f "$CURRENT_THEME_DIR/ghostty" ]]; then
    touch "$CURRENT_THEME_DIR/ghostty"
fi

if [[ ! -f "$CURRENT_THEME_DIR/tmux" ]]; then
    touch "$CURRENT_THEME_DIR/tmux"
fi

omarchy-theme-bg-next

# Restart components to apply new theme
pkill -SIGUSR2 btop
makoctl reload
hyprctl reload

