#!/bin/bash
# omarchy-gtk-theme-sync: make Nautilus (and other GTK3/GTK4/libadwaita apps)
# follow the active Omarchy theme's colors, not just its light/dark mode.
#
# Omarchy ships no GTK color template, so this adds one:
#   ~/.config/omarchy/themed/gtk.css.tpl           color template, rendered per theme
#   ~/.config/omarchy/hooks/theme-set.d/20-gtk-colors   copies the result to GTK's config
#   ~/.local/share/nautilus-python/extensions/omarchy_theme_live.py
#                                                  live-reloads the theme colors inside Nautilus
# All of these live in your home directory, so `omarchy update` leaves them alone.
#
# Usage: omarchy-gtk-theme-sync <install|uninstall|status> [--icons] [--force]
#   --icons   (install) remove theme-set hooks that pin a fixed GTK icon theme, so
#             folder/icon colors follow each Omarchy theme. Hooks are backed up.
#   --force   (install) overwrite a gtk.css this script did not create.

set -euo pipefail

MARK="Generated by omarchy-gtk-theme-sync"
CONFIG="$HOME/.config"
TEMPLATE="$CONFIG/omarchy/themed/gtk.css.tpl"
HOOK_DIR="$CONFIG/omarchy/hooks/theme-set.d"
HOOK="$HOOK_DIR/20-gtk-colors"
GTK_DIRS=("$CONFIG/gtk-3.0" "$CONFIG/gtk-4.0")
EXT="$HOME/.local/share/nautilus-python/extensions/omarchy_theme_live.py"

die() { echo "error: $*" >&2; exit 1; }
say() { echo "==> $*"; }

usage() {
  sed -n '2,/^$/p' "$0" | sed 's/^# \{0,1\}//'
  exit "${1:-0}"
}

require_omarchy() {
  command -v omarchy >/dev/null || die "omarchy is not on PATH; this is for Omarchy 4.x"
  [[ -x $(command -v omarchy-theme-set-templates) ]] || die "this Omarchy has no theme template engine"
  [[ -f $HOME/.local/state/omarchy/current/theme.name ]] || die "no active Omarchy theme found"
}

write_template() {
  mkdir -p "$(dirname "$TEMPLATE")"
  cat >"$TEMPLATE" <<'TPL'
/* Generated by omarchy-gtk-theme-sync: GTK4/libadwaita (Nautilus) and GTK3 colors from the Omarchy theme. */

@define-color accent_color {{ accent }};
@define-color accent_bg_color {{ accent }};
@define-color accent_fg_color {{ background }};

@define-color window_bg_color {{ background }};
@define-color window_fg_color {{ foreground }};

@define-color view_bg_color {{ background }};
@define-color view_fg_color {{ foreground }};

@define-color headerbar_bg_color {{ dark_background }};
@define-color headerbar_fg_color {{ foreground }};
@define-color headerbar_border_color {{ mix background foreground 10% }};
@define-color headerbar_backdrop_color {{ background }};
@define-color headerbar_shade_color rgba(0, 0, 0, 0.36);

@define-color sidebar_bg_color {{ dark_background }};
@define-color sidebar_fg_color {{ foreground }};
@define-color sidebar_backdrop_color {{ background }};
@define-color sidebar_shade_color rgba(0, 0, 0, 0.36);

@define-color secondary_sidebar_bg_color {{ dark_background }};
@define-color secondary_sidebar_fg_color {{ foreground }};
@define-color secondary_sidebar_backdrop_color {{ background }};
@define-color secondary_sidebar_shade_color rgba(0, 0, 0, 0.36);

@define-color card_bg_color {{ mix background foreground 6% }};
@define-color card_fg_color {{ foreground }};
@define-color card_shade_color rgba(0, 0, 0, 0.36);

@define-color dialog_bg_color {{ background }};
@define-color dialog_fg_color {{ foreground }};

@define-color popover_bg_color {{ lighter_background }};
@define-color popover_fg_color {{ foreground }};
@define-color popover_shade_color rgba(0, 0, 0, 0.36);

@define-color thumbnail_bg_color {{ lighter_background }};
@define-color thumbnail_fg_color {{ foreground }};

@define-color shade_color rgba(0, 0, 0, 0.36);
@define-color scrollbar_outline_color {{ background }};

@define-color destructive_color {{ red }};
@define-color destructive_bg_color {{ red }};
@define-color destructive_fg_color {{ background }};
@define-color success_color {{ green }};
@define-color success_bg_color {{ green }};
@define-color success_fg_color {{ background }};
@define-color warning_color {{ yellow }};
@define-color warning_bg_color {{ yellow }};
@define-color warning_fg_color {{ background }};
@define-color error_color {{ red }};
@define-color error_bg_color {{ red }};
@define-color error_fg_color {{ background }};
TPL
}

write_hook() {
  mkdir -p "$HOOK_DIR"
  cat >"$HOOK" <<'HOOK'
#!/bin/bash
# Generated by omarchy-gtk-theme-sync: install the themed gtk.css for GTK apps.
src="$HOME/.local/state/omarchy/current/theme/gtk.css"
[[ -f $src ]] || exit 0

for dir in gtk-3.0 gtk-4.0; do
  mkdir -p "$HOME/.config/$dir"
  cp "$src" "$HOME/.config/$dir/gtk.css"
done

HOOK
  chmod +x "$HOOK"
}

write_extension() {
  mkdir -p "$(dirname "$EXT")"
  cat >"$EXT" <<'PY'
# Generated by omarchy-gtk-theme-sync: recolor Nautilus live when the Omarchy theme changes.
# GTK reads ~/.config/gtk-4.0/gtk.css once at startup. This loads the theme's gtk.css as an
# extra style provider inside the Nautilus process and reloads it the moment Omarchy swaps in
# a new theme directory, without waiting for the theme-set hooks, which run last.
import os

import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Gdk", "4.0")
from gi.repository import Gdk, Gio, GLib, Gtk  # noqa: E402

STATE_DIR = os.path.expanduser("~/.local/state/omarchy/current")
CSS_PATHS = (
    os.path.join(STATE_DIR, "theme", "gtk.css"),
    os.path.expanduser("~/.config/gtk-4.0/gtk.css"),
)
DEBOUNCE_MS = 40

_state = {}


def _reload():
    _state.pop("pending", None)
    for path in CSS_PATHS:
        try:
            _state["provider"].load_from_path(path)
            break
        except GLib.Error:
            continue  # theme dir mid-swap or file missing; the next event retries
    return GLib.SOURCE_REMOVE


def _on_change(_monitor, _file, _other, _event):
    # Omarchy does rm -rf then mv on the theme dir; collapse those events into one reload.
    if "pending" not in _state:
        _state["pending"] = GLib.timeout_add(DEBOUNCE_MS, _reload)


def _setup():
    display = Gdk.Display.get_default()
    if display is None:
        return GLib.SOURCE_CONTINUE
    provider = Gtk.CssProvider()
    _state["provider"] = provider
    _reload()
    # One step above the user's own gtk.css so these colors always win.
    Gtk.StyleContext.add_provider_for_display(display, provider, Gtk.STYLE_PROVIDER_PRIORITY_USER + 1)
    for watched in (STATE_DIR, os.path.dirname(CSS_PATHS[1])):
        if os.path.isdir(watched):
            monitor = Gio.File.new_for_path(watched).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None)
            monitor.connect("changed", _on_change)
            _state[watched] = monitor
    return GLib.SOURCE_REMOVE


GLib.idle_add(_setup)
PY
}

# A gtk.css we did not write is the user's; keep it unless told otherwise.
guard_foreign_css() {
  local dir file
  for dir in "${GTK_DIRS[@]}"; do
    file="$dir/gtk.css"
    [[ -f $file ]] || continue
    grep -q "$MARK" "$file" && continue
    if [[ $force == 1 ]]; then
      cp "$file" "$file.bak.$(date +%s)"
      say "backed up existing $file"
    else
      die "$file exists and was not created by this script (use --force to back it up and replace it)"
    fi
  done
}

# Hooks that pin an icon theme fight Omarchy's per-theme Yaru color, which is why
# folders flash to the theme color and then revert. Back them up, then remove.
drop_icon_pin_hooks() {
  local hook found=0
  [[ -d $HOOK_DIR ]] || return 0
  for hook in "$HOOK_DIR"/*; do
    [[ -f $hook && $hook != "$HOOK" ]] || continue
    grep -q "org.gnome.desktop.interface icon-theme" "$hook" || continue
    cp "$hook" "$hook.bak.$(date +%s)"
    rm "$hook"
    say "removed icon-pinning hook $(basename "$hook") (backup: $hook.bak.*)"
    found=1
  done
  [[ $found == 1 ]] || say "no icon-pinning hooks found"
}

install_all() {
  require_omarchy
  guard_foreign_css
  write_template
  write_hook
  write_extension
  say "wrote $TEMPLATE"
  say "wrote $HOOK"
  say "wrote $EXT"
  [[ $icons == 1 ]] && drop_icon_pin_hooks
  say "rendering the current theme (wallpaper is left alone)"
  omarchy theme refresh >/dev/null 2>&1 || true
  for dir in "${GTK_DIRS[@]}"; do
    [[ -f $dir/gtk.css ]] || die "$dir/gtk.css was not created; run 'omarchy theme refresh' and check for errors"
  done
  say "done. Restart Nautilus once to load the extension: nautilus --quit"
  say "after that, open Nautilus windows recolor live on every theme change."
}

uninstall_all() {
  local dir file
  rm -f "$TEMPLATE" "$HOOK" "$EXT"
  say "removed template, hook and Nautilus extension"
  for dir in "${GTK_DIRS[@]}"; do
    file="$dir/gtk.css"
    if [[ -f $file ]] && grep -q "$MARK" "$file"; then
      rm "$file"
      say "removed $file"
    fi
  done
}

status_all() {
  local dir
  [[ -f $TEMPLATE ]] && echo "template: installed" || echo "template: missing"
  [[ -x $HOOK ]] && echo "hook:     installed" || echo "hook:     missing"
  [[ -f $EXT ]] && echo "live-reload extension: installed" || echo "live-reload extension: missing"
  for dir in "${GTK_DIRS[@]}"; do
    if [[ -f $dir/gtk.css ]] && grep -q "$MARK" "$dir/gtk.css"; then
      echo "$(basename "$dir"): themed ($(grep -m1 window_bg_color "$dir/gtk.css"))"
    else
      echo "$(basename "$dir"): not managed"
    fi
  done
}

icons=0
force=0
cmd=""
for arg in "$@"; do
  case $arg in
    install | uninstall | status) cmd=$arg ;;
    --icons) icons=1 ;;
    --force) force=1 ;;
    -h | --help) usage 0 ;;
    *) echo "unknown argument: $arg" >&2; usage 1 ;;
  esac
done

case $cmd in
  install) install_all ;;
  uninstall) uninstall_all ;;
  status) status_all ;;
  *) usage 1 ;;
esac
