#!/usr/bin/env 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)

# desktop-sync, where installed, owns the GTK theme and the icon theme: it swaps
# the look the desktop already has between that family's own light and dark
# variants, and a gtk-theme of Adwaita here would replace the family outright.
# Only its package creates the directory. color-scheme is still written, because
# that is the mode desktop-sync follows.
desktop_sync_owns_look() {
  [[ -d ${OMARCHY_DESKTOP_SYNC_DIR:-/etc/desktop-sync} ]]
}

if [[ $mode == "light" ]]; then
  gsettings set org.gnome.desktop.interface color-scheme "prefer-light"
  desktop_sync_owns_look || gsettings set org.gnome.desktop.interface gtk-theme "Adwaita"
else
  gsettings set org.gnome.desktop.interface color-scheme "prefer-dark"
  desktop_sync_owns_look || gsettings set org.gnome.desktop.interface gtk-theme "Adwaita-dark"
fi

desktop_sync_owns_look && exit 0

# Change gnome icon theme color
GNOME_ICONS_THEME=$HOME/.local/state/omarchy/current/theme/icons.theme
if [[ -f $GNOME_ICONS_THEME ]]; then
  gsettings set org.gnome.desktop.interface icon-theme "$(<$GNOME_ICONS_THEME)"
else
  gsettings set org.gnome.desktop.interface icon-theme "Yaru-blue"
fi
