#!/usr/bin/env bash
# tanin-libadwaita {dark|light|auto|watch}
#   Activates the Fuji recolour for BOTH GTK4/libadwaita and GTK3 by symlinking
#   the chosen variant into ~/.config/gtk-{4.0,3.0}/gtk.css.
#     dark|light  set that mode (and the GNOME color-scheme + gtk-theme)
#     auto        follow the CURRENT color-scheme once (don't change it)
#     watch       follow color-scheme changes live (daemon) — the appearance
#                 toggle in settings then drives light/dark automatically
set -euo pipefail

SHARE="${TANIN_LIBADWAITA_DIR:-/usr/share/tanin/libadwaita}"
CFG="${XDG_CONFIG_HOME:-$HOME/.config}"

# Symlink both toolkits' gtk.css to the variant + pick the matching adw-gtk3.
# Does NOT touch color-scheme (so it's safe to call from a color-scheme watcher).
link_variant() {
  local mode="$1" gtktheme
  case "$mode" in
    dark)  gtktheme="adw-gtk3-dark" ;;
    light) gtktheme="adw-gtk3" ;;
    *) return 2 ;;
  esac
  local v src dst
  for v in gtk-4.0 gtk-3.0; do
    src="$SHARE/$v/$mode.css"; dst="$CFG/$v/gtk.css"
    [ -f "$src" ] || continue
    mkdir -p "$CFG/$v"
    if [ -e "$dst" ] && [ ! -L "$dst" ] && [ ! -e "$dst.pre-tanin" ]; then
      cp -a "$dst" "$dst.pre-tanin"      # back up a real file once
    fi
    ln -sf "$src" "$dst"
  done
  gsettings set org.gnome.desktop.interface gtk-theme "$gtktheme" 2>/dev/null || true
  gsettings set org.gnome.desktop.interface accent-color "purple" 2>/dev/null || true
  echo "tanin-libadwaita: $mode"
}

current_mode() {
  case "$(gsettings get org.gnome.desktop.interface color-scheme 2>/dev/null)" in
    *prefer-light*) echo light ;;
    *)              echo dark  ;;
  esac
}

case "${1:-auto}" in
  dark|light)
    link_variant "$1"
    gsettings set org.gnome.desktop.interface color-scheme \
      "$([ "$1" = light ] && echo prefer-light || echo prefer-dark)" 2>/dev/null || true
    ;;
  auto)
    link_variant "$(current_mode)"
    ;;
  watch)
    link_variant "$(current_mode)"
    gsettings monitor org.gnome.desktop.interface color-scheme | while read -r _; do
      link_variant "$(current_mode)"
    done
    ;;
  *)
    echo "usage: tanin-libadwaita {dark|light|auto|watch}" >&2; exit 2 ;;
esac
