#!/usr/bin/env bash

# Common XKB behavior should be discoverable without hiding the raw option
# string from advanced users. This is source-only so it never remaps the live
# keyboard while the desktop is in use.

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
page="$repo_dir/config/dot/quickshell/modules/settings/ShortcutsPage.qml"
input="$repo_dir/config/dot/hypr/input.lua"
schema="$repo_dir/config/dot/quickshell/config/PreferenceSchema.qml"

fail() {
    printf 'xkb presets contract: %s\n' "$1" >&2
    exit 1
}

for needle in \
    'function currentXkbOption(prefix: string): string' \
    'function setXkbOption(prefix: string, option: string): void' \
    'label: "Caps Lock"' \
    'value: "caps:escape_shifted_capslock"' \
    'value: "caps:ctrl_modifier"' \
    'label: "Compose key"' \
    'value: "compose:ralt"' \
    'label: "Layout switching"' \
    'value: "grp:win_space_toggle"' \
    'SystemSettings.commitPreference("keyboardOptions"' \
    'TextEntryRow { setting: "keyboardOptions"'; do
    rg -Fq "$needle" "$page" || fail "Shortcuts is missing $needle"
done

# Picking one category must replace only that category, preserving advanced
# options from every other group.
rg -Fq 'option.indexOf(prefix) !== 0' "$page" \
    || fail 'preset updates do not preserve unrelated XKB options'

rg -Fq 'kb_variant = prefs.get("keyboardVariant", "")' "$input" \
    || fail 'Hyprland does not replay the stored keyboard variant'
rg -Fq 'key: "keyboardOptions", type: "string", def: "caps:escape_shifted_capslock"' "$schema" \
    || fail 'the shipped XKB default no longer matches the migrated GNOME behavior'
rg -Fq 'kb_options = prefs.get("keyboardOptions", "caps:escape_shifted_capslock")' "$input" \
    || fail 'Hyprland does not replay the stored keyboard options'

printf 'xkb presets contract: PASS\n'
