#!/bin/bash

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

# Detect mode (light|dark) with this precedence:
#   1. `mode` key in the active theme's colors.toml
#   2. legacy `light.mode` file shipped beside the theme
THEME_DIR=~/.config/omarchy/current/theme
COLORS_FILE="$THEME_DIR/colors.toml"

theme_color() {
  local key="$1"

  awk -F= -v key="$key" '
    {
      field = $1
      gsub(/^[[:space:]]+|[[:space:]]+$/, "", field)
      if (field == key) {
        value = $2
        gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
        if (value ~ /^"/) {
          sub(/^"/, "", value)
          sub(/".*$/, "", value)
        }
        print value
        exit
      }
    }
  ' "$COLORS_FILE"
}

mode=""
if [[ -f $COLORS_FILE ]]; then
  mode=$(theme_color mode)
fi
if [[ -z $mode && -f $THEME_DIR/light.mode ]]; then
  mode="light"
fi

if [[ $mode == "light" ]]; 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
GNOME_ICONS_THEME=~/.config/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
