#!/bin/sh
# chandra-kde-colors dark|light
#
# Point KDE / Qt apps at a dark or light color scheme: called by the compositor when the Settings
# Dark mode switch flips (compositor/host/system_theme.mbt), in the login session only.
#
# KDE apps (KWrite, Kate, Dolphin, Okular...) don't read a scheme by its name: KColorScheme reads
# the [Colors:*] groups of ~/.config/kdeglobals, which Plasma's tools copy in from the scheme's
# .colors file. Setting only [General] ColorScheme=BreezeDark (what kwriteconfig did here before)
# leaves those groups as they were, or missing, and apps fall back to their built-in light
# colors. So this copies the scheme's color groups into kdeglobals itself, which needs neither
# Plasma, kded nor plasma-apply-colorscheme, then tells running apps (the KDE platform theme,
# QT_QPA_PLATFORMTHEME=kde) to repaint.
#
# The scheme: the dark/light counterpart of the current one when it has one (FooLight <->
# FooDark), else BreezeDark/BreezeLight, else Chandra's own ChandraDark/ChandraLight
# (session/color-schemes, installed to /usr/local/share/color-schemes).
set -u
case "${1:-}" in
  dark) from=light to=dark defaults="BreezeDark ChandraDark" ;;
  light) from=dark to=light defaults="BreezeLight ChandraLight" ;;
  *) echo "usage: chandra-kde-colors dark|light" >&2; exit 2 ;;
esac

cfg="${XDG_CONFIG_HOME:-$HOME/.config}"
kg="$cfg/kdeglobals"
dirs="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"

scheme_file() {  # NAME -> path of NAME.colors in the data dirs, if any
  old_ifs=$IFS; IFS=:
  for d in $dirs; do
    if [ -n "$d" ] && [ -f "$d/color-schemes/$1.colors" ]; then
      IFS=$old_ifs; printf '%s\n' "$d/color-schemes/$1.colors"; return 0
    fi
  done
  IFS=$old_ifs; return 1
}

current=""
[ -f "$kg" ] && current=$(sed -n '/^\[General\]/,/^\[/s/^ColorScheme=//p' "$kg" | head -n 1)
name="" file=""
if [ -n "$current" ]; then
  # Keep the case: MyLight -> MyDark, my-light -> my-dark, MYLIGHT -> MYDARK.
  F=$(printf '%s' "$from" | sed 's/^./\U&/') T=$(printf '%s' "$to" | sed 's/^./\U&/')
  UF=$(printf '%s' "$from" | tr a-z A-Z) UT=$(printf '%s' "$to" | tr a-z A-Z)
  other=$(printf '%s' "$current" | sed "s/$F/$T/;t;s/$from/$to/;t;s/$UF/$UT/")
  if [ "$other" != "$current" ] && file=$(scheme_file "$other"); then name=$other; fi
fi
if [ -z "$name" ]; then
  for n in $defaults; do
    if file=$(scheme_file "$n"); then name=$n; break; fi
  done
fi
if [ -z "$name" ]; then
  echo "chandra-kde-colors: no $to color scheme found in $dirs" >&2
  exit 1
fi

mkdir -p "$cfg" || exit 1
[ -f "$kg" ] || : >"$kg"
# kdeglobals without its color groups (and with ColorScheme=NAME in [General]), then the
# scheme's color groups.
awk -v name="$name" -v kg="$kg" '
  function colors(g) { return g ~ /^\[(Colors:|ColorEffects:|WM\])/ }
  FILENAME == kg {
    if ($0 ~ /^\[/) {
      group = $0
      if (group == "[General]") { general = 1 }
      skip = colors(group)
    }
    if (skip) next
    if (group == "[General]" && $0 ~ /^ColorScheme=/) next
    print
    if ($0 == "[General]") print "ColorScheme=" name
    next
  }
  FNR == 1 {
    if (!general) { print ""; print "[General]"; print "ColorScheme=" name }
    print ""
  }
  /^\[/ { group = $0; keep = colors(group) }
  keep { print }
' "$kg" "$file" >"$kg.chandra-new" && mv "$kg.chandra-new" "$kg" || exit 1

# Running apps: the KDE platform theme reloads its palette on KGlobalSettings.notifyChange
# (0 = PaletteChanged); KConfigWatcher users listen for kconfig ConfigChanged.
if command -v dbus-send >/dev/null 2>&1; then
  dbus-send --session --type=signal /KGlobalSettings org.kde.KGlobalSettings.notifyChange \
    int32:0 int32:0 2>/dev/null
elif command -v gdbus >/dev/null 2>&1; then
  gdbus emit --session --object-path /KGlobalSettings \
    --signal org.kde.KGlobalSettings.notifyChange 0 0 >/dev/null 2>&1
fi
if command -v gdbus >/dev/null 2>&1; then
  gdbus emit --session --object-path /kdeglobals --signal org.kde.kconfig.notify.ConfigChanged \
    "{'General': [b'ColorScheme'], 'Colors:Window': [b'BackgroundNormal'], 'Colors:View': [b'BackgroundNormal']}" \
    >/dev/null 2>&1
fi
printf '%s\n' "$name"
true
