#!/bin/bash
# summary: Check that desktop settings never move the pointer.
# Starchaser never moves the pointer.
# Fails (exit 1) if anything in the given trees moves or warps it: Hyprland cursor moves, warp options turned on,
# pointer-faking tools, cursor.default_monitor left set, or a workspace move outside the pointer-safe helper.
# Also fails if the Starchaser hyprland.lua stops setting cursor.no_warps = true. Exit 2: a path you gave doesn't exist.
#
#     starchaser check pointer [path ...]     default: $REPO (or ~/starchaser) plus the user's hypr/quickshell/bin
#
# Owner rule, 2026-10-03: "no mouse snapping - dont move my mouse!!" (lines 3-8 above are the --help text)
# The desktop setup runs this on the repo and refuses to continue if it fails.
set -uo pipefail
# the checkout: the one this script is in (run from a checkout's bin/), else the installed machine's copy, else the
# system's. A folder counts only when it holds config/hypr/hyprland.lua (an installed /usr/bin/.. is not a checkout)
here=$(dirname "$(readlink -f "$0")")/..
DEFAULT_REPO=$HOME/.local/share/starchaser/repo
for r in "$here" "$HOME/.local/share/starchaser/repo" /usr/share/starchaser; do
  [ -f "$r/config/hypr/hyprland.lua" ] && { DEFAULT_REPO=$(readlink -f "$r"); break; }
done
REPO=${REPO:-$DEFAULT_REPO}
case "${1:-}" in
    -h|--help|help) sed -n '3,8p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    -*) echo "starchaser check pointer: unknown option $1. Run 'starchaser check pointer --help' for more help." >&2; exit 2 ;;
esac
explicit=0
[ $# -gt 0 ] && explicit=1
[ $# -gt 0 ] || set -- "$REPO" "$HOME/.config/hypr" "$HOME/.config/quickshell" "$HOME/.local/bin"
SELF=$(readlink -f "$0")

# The detector's own lines read like the violations it reports. Skip every copy of this script, not only the
# one running (a tree checked from another install holds another copy, e.g. the installed repo checked from a
# checkout), so the checker never reports itself.
self_file() {
    case "${1##*/}" in starchaser-check-pointer) return 0 ;; esac
    [ "$(readlink -f "$1")" = "$SELF" ]
}

# Each alternative is a way something moves the pointer. Built from pieces so this file doesn't match itself.
c=cursor; m=move; t=to
PAT="${c}\\.${m}\\b|${m}${c}|${m}_${c}|ydotool +mouse${m}|dotool.*mouse${t}|wlrctl +pointer +${m}"
PAT+="|no_warps *= *false|persistent_warps *= *true|warp_on_change_workspace *= *[1-9]|warp_on_toggle_special *= *[1-9]"
PAT+="|warp_back_after_non_mouse_input *= *true"

# Two things Hyprland 0.56 warps the pointer for even with cursor.no_warps on (QA finding 003):
# - cursor.default_monitor: a forced warp to that screen the first time it is plugged in while the option is set. It
#   is allowed only in the login-only shape starchaser displays writes: the line before it tests
#   `#hl.get_monitors() == 0` (the first config load) and the line after it clears it again on hyprland.start.
# - hl.dsp.workspace.move of the workspace shown on the screen that has focus: a warp to the target screen's center.
#   Every workspace move goes through StarchaserWS.moveWorkspace (config/hypr/workspaces.lua), which moves focus
#   first; its one dispatch line carries the marker below.
dm=default_monitor
DM_SET="(^|[^[:alnum:]_])${dm}[[:space:]]*=[[:space:]]*([^\"[:space:]]|\"[^\"])"
WS_MOVE="dsp\\.workspace\\.${m}[[:space:]]*\\("
WS_MARK="-- the one workspace ${m}"

bad=0; missing=0      # missing: a path you named does not exist (exit 2, whatever else was found)
for p in "$@"; do
    if [ ! -e "$p" ]; then
        # A folder you named has to exist; the default ones (say, no ~/.config/quickshell yet) may be missing.
        [ $explicit = 1 ] && { echo "NOT FOUND: $p" >&2; missing=1; }
        continue
    fi
    while IFS= read -r hit; do
        f=${hit%%:*}
        self_file "$f" && continue
        # Files' own settings list moves its keyboard selection by a row count, and the Open/Save window's type-to-find
        # lands its selection on a found row (methods of Flea's, in its patches): the selection, not the pointer
        case "$f" in */packages/flea/*.patch|packages/flea/*.patch)
            # This catalog key names keyboard selection in the shortcut sheet.
            [[ ${hit#*:*:} == *'label: Text::Key('*'"settings.keys.'"${m}_${c}"'"'* ]] && continue
            [[ ${hit#*:*:} =~ ^[\ +-][[:space:]]*fn\ ${m}_${c}\(\&mut\ self,\ delta:\ isize\)\ \{$ ]] && continue
            [[ ${hit#*:*:} =~ ^[\ +-][[:space:]]*self\.${m}_${c}\(index,\ cx\)\;$ ]] && continue ;;
        esac
        echo "MOVES THE POINTER: $hit"; bad=1
    done < <(grep -rInE "$PAT" "$p" --exclude-dir=.git --exclude-dir=__pycache__ --exclude='*.bak*' --exclude='*.orig' 2>/dev/null)
    while IFS= read -r f; do
        self_file "$f" && continue
        while IFS= read -r hit; do
            echo "MOVES THE POINTER: $f:$hit"
            echo "   cursor.default_monitor left set: Hyprland warps the pointer onto that screen (past no_warps) when it is"
            echo "   plugged in. Set it only in the login-only block starchaser displays writes; an older monitors.lua is"
            echo "   fixed by running: starchaser displays migrate"
            bad=1
        done < <(awk -v re="$DM_SET" '
            { line[NR] = $0 }
            END {
                prev = ""
                for (i = 1; i <= NR; i++) {
                    l = line[i]
                    if (l ~ re && !(prev ~ /#hl\.get_monitors\(\) == 0/ && line[i + 1] ~ /hyprland\.start/ \
                                    && index(line[i + 1], "default_monitor = \"\"") > 0))
                        print i ": " l
                    if (l !~ /^[[:space:]]*$/ && l !~ /^[[:space:]]*(--|#)/) prev = l
                }
            }' "$f")
    done < <(grep -rlIE "$DM_SET" "$p" --exclude-dir=.git --exclude-dir=__pycache__ --exclude='*.bak*' --exclude='*.orig' 2>/dev/null)
    while IFS= read -r hit; do
        f=${hit%%:*}
        self_file "$f" && continue
        case "$f" in */config/hypr/workspaces.lua|config/hypr/workspaces.lua|*/.config/hypr/workspaces.lua)
            [[ $hit == *"$WS_MARK"* ]] && continue ;;
        esac
        echo "MOVES THE POINTER: $hit"
        echo "   a workspace move warps the pointer when that workspace is shown on the focused screen: call"
        echo "   StarchaserWS.moveWorkspace(id, screen) instead (it moves focus first, never the pointer)"
        bad=1
    done < <(grep -rHInE "$WS_MOVE" "$p" --exclude-dir=.git --exclude-dir=__pycache__ --exclude='*.bak*' --exclude='*.orig' 2>/dev/null)
done

hl=$REPO/config/hypr/hyprland.lua
if [ -f "$hl" ] && ! grep -qE 'no_warps *= *true' "$hl"; then
    echo "MISSING: $hl must set cursor = { no_warps = true }"; bad=1
fi

[ $bad = 1 ] && echo "Starchaser never moves the pointer. Remove the lines above."
[ $missing = 1 ] && echo "Not checked: a folder or file above doesn't exist." >&2
[ $bad = 0 ] && [ $missing = 0 ] && echo "OK: nothing moves the pointer"
[ $missing = 1 ] && exit 2
exit $bad
