#!/bin/bash

# omarchy:summary=Apply the current theme to GNOME color mode and icon settings
# omarchy:hidden=true

# gsettings needs a user DBus session. During ISO installs this command can be
# reached from arch-chroot while applying the initial Omarchy theme; defer until
# the user has a real session instead of emitting dconf warnings.
if [[ -z ${DBUS_SESSION_BUS_ADDRESS:-} ]]; then
  exit 0
fi

THEME_DIR=$HOME/.local/state/omarchy/current/theme
COLORS_FILE="$THEME_DIR/colors.toml"

# omarchy-theme-color resolves mode from colors.toml (`mode = "light"`), a
# legacy light.mode marker beside it, or background luminance for user themes.
mode=$(omarchy-theme-color --file "$COLORS_FILE" mode)

current_dconf=$(dconf dump /org/gnome/desktop/interface/ 2>/dev/null || true)
set_if_changed() {
  local key="$1" value="$2"

  [[ $'\n'$current_dconf$'\n' == *$'\n'"$key='$value'"$'\n'* ]] && return 0
  gsettings set org.gnome.desktop.interface "$key" "$value"
}

if [[ $mode == "light" ]]; then
  set_if_changed color-scheme "prefer-light"
  set_if_changed gtk-theme "Adwaita"
else
  set_if_changed color-scheme "prefer-dark"
  set_if_changed gtk-theme "Adwaita-dark"
fi

# Every theme uses the Adwaita icons, which GTK brings along.
set_if_changed icon-theme "Adwaita"
