#!/usr/bin/env bash

# Propagates the colour scheme to applications that do not read the desktop
# portal.
#
# Most modern applications DO follow org.freedesktop.portal.Settings and need
# nothing from us: GTK4/libadwaita, Qt6, Chromium and Electron all read
# org.freedesktop.appearance color-scheme, which xdg-desktop-portal-gtk serves
# from gsettings. Panama sets that, so those follow automatically.
#
# Terminals are the notable exception -- they predate the standard and carry
# their own palettes. kitty is handled here.
#
#   panama-theme-apps dark|light
#
# kitty gets it twice: the generated include file so terminals opened later
# start correct, and a live `set-colors` over its control socket so terminals
# already open change now. Without the second, a scheme change appears to do
# nothing until you open a new window.

set -euo pipefail

scheme="${1:-dark}"
case "$scheme" in
    dark|light) ;;
    *) printf 'usage: panama-theme-apps [dark|light]\n' >&2; exit 2 ;;
esac

kitty_dir="${XDG_CONFIG_HOME:-$HOME/.config}/kitty"
theme_file="$kitty_dir/themes/tokyonight-moon.conf"
[[ "$scheme" == "light" ]] && theme_file="$kitty_dir/themes/tokyonight-day.conf"

status_kitty="skipped"
if [[ -r "$theme_file" ]]; then
    # Written atomically: kitty may read this while a new window is starting.
    if cp "$theme_file" "$kitty_dir/current-theme.conf.tmp" 2>/dev/null \
        && mv "$kitty_dir/current-theme.conf.tmp" "$kitty_dir/current-theme.conf" 2>/dev/null; then
        status_kitty="written"
    fi

    # Live-apply to running terminals. kitty appends its PID to the socket name
    # from listen_on, so there is one socket per instance -- "unix:@mykitty"
    # alone reaches nothing, which is exactly how this looked like remote
    # control being disabled when it was not.
    if command -v kitty >/dev/null 2>&1 && command -v ss >/dev/null 2>&1; then
        applied=0
        while read -r socket; do
            [[ -n "$socket" ]] || continue
            if kitty @ --to "unix:@${socket#@}" set-colors --all --configured "$theme_file" >/dev/null 2>&1; then
                applied=$((applied + 1))
            fi
        done < <(ss -xl 2>/dev/null | grep -oE '@mykitty[^[:space:]]*' | sort -u)
        (( applied > 0 )) && status_kitty="applied to $applied"
    fi
fi

printf '{"scheme":"%s","kitty":"%s"}\n' "$scheme" "$status_kitty"
