#!/bin/sh
# Sets GTK's window button layout for the cont8nuum session: none, since
# cont8nuum has no window buttons. GTK on Wayland reads it from GSettings
# (org.gnome.desktop.wm.preferences, also through the Settings portal);
# settings.ini covers GTK without GSettings schemas. Both are shared with
# other desktops: Plasma's kde-gtk-config writes its own value back when
# Plasma starts. C8_GTK_BUTTONS overrides the layout (GTK's syntax, e.g.
# "appmenu:close"; an empty value leaves everything as it is).
layout=${C8_GTK_BUTTONS-:}
[ -n "$layout" ] || exit 0

if command -v gsettings >/dev/null 2>&1 &&
	gsettings writable org.gnome.desktop.wm.preferences button-layout \
		>/dev/null 2>&1; then
	gsettings set org.gnome.desktop.wm.preferences button-layout "$layout"
fi

config=${XDG_CONFIG_HOME:-$HOME/.config}
for v in 3.0 4.0; do
	f=$config/gtk-$v/settings.ini
	mkdir -p "${f%/*}"
	if [ ! -e "$f" ]; then
		printf '[Settings]\ngtk-decoration-layout=%s\n' "$layout" >"$f"
	elif grep -q '^gtk-decoration-layout=' "$f"; then
		grep -qx "gtk-decoration-layout=$layout" "$f" ||
			sed -i "s|^gtk-decoration-layout=.*|gtk-decoration-layout=$layout|" "$f"
	elif grep -q '^\[Settings\]' "$f"; then
		sed -i "/^\[Settings\]/a gtk-decoration-layout=$layout" "$f"
	else
		printf '\n[Settings]\ngtk-decoration-layout=%s\n' "$layout" >>"$f"
	fi
done
exit 0
