#!/bin/bash
# Qt 6.12 ships a QtQuick `Color` singleton that shadows the shell's own
# qs.Commons `Color` palette, so every Color.bar.* / Color.polkit.* resolves to
# undefined: the bar is a black strip with no widgets, and the lock screen and
# polkit dialog lose their colours. Omarchy <= 4.0.4 still has the clash.
#
# The fix renames the shell's singleton to ShellColor and rewrites its users.
# An omarchy package upgrade puts the stock files back, so this is idempotent
# and safe to re-run after every update; it does nothing once upstream renames
# the singleton itself.
#
#   omarchy-fix-qt-color [--check] [shell-dir]   (default /usr/share/omarchy/shell)
set -euo pipefail

check=0
[[ ${1-} == --check ]] && { check=1; shift; }
shell=${1:-/usr/share/omarchy/shell}
qmldir=$shell/Commons/qmldir

[[ -f $qmldir ]] || { echo "no $qmldir - not an Omarchy shell" >&2; exit 2; }
if ! grep -q '^singleton Color ' "$qmldir"; then
  echo "= shell Color singleton not present (already renamed, or fixed upstream)"
  exit 0
fi
qt=$(pacman -Q qt6-declarative 2>/dev/null | awk '{print $2}') || true
if [[ -n $qt ]] && [[ $(vercmp "$qt" 6.12) -lt 0 ]]; then
  echo "= qt6-declarative $qt predates the Color clash; nothing to do"
  exit 0
fi
(( check )) && { echo "! shell needs the Qt Color fix (qt6-declarative $qt)"; exit 1; }

sudo=(); [[ -w $qmldir ]] || sudo=(sudo)
backup=$shell.bak-qt612
[[ -e $backup ]] || "${sudo[@]}" cp -a "$shell" "$backup"

"${sudo[@]}" sed -i 's/^singleton Color /singleton ShellColor /' "$qmldir"
find "$shell" -type f \( -name '*.qml' -o -name '*.js' \) -print0 \
  | xargs -0 grep -lZE '(^|[^A-Za-z0-9_."/])Color\.' \
  | xargs -0 -r "${sudo[@]}" sed -i -E 's/(^|[^A-Za-z0-9_."\/])Color\./\1ShellColor./g'
echo "+ renamed the shell's Color singleton to ShellColor (backup: $backup)"
echo "  restart the shell to pick it up: omarchy-restart-shell"
