#!/usr/bin/env bash
#
# Registers Handy's dictation shortcuts as GNOME custom keybindings.
#
# Under Wayland an application cannot grab a global hotkey, so Handy's own
# shortcut setting never fires. GNOME holds the keys instead and runs Handy's
# CLI, which signals the already-running instance.
#
# Entries are matched by name, so re-running updates them in place. Slots are
# allocated around everything already present in dconf, including entries other
# applications have orphaned by dropping them from the list but leaving their
# keys behind.

set -u

schema=org.gnome.settings-daemon.plugins.media-keys
entry_schema=$schema.custom-keybinding
dconf_dir=/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings

# name|command|binding
shortcuts=(
    'Handy: toggle dictation|/usr/bin/handy --toggle-transcription|<Control><Super>space'
    'Handy: cancel dictation|/usr/bin/handy --cancel|<Control><Super>BackSpace'
)

if ! command -v gsettings >/dev/null; then
    printf >&2 '%s\n' 'gsettings not found; these shortcuts require GNOME.'
    exit 1
fi

# Strips the single quotes GVariant wraps around string values.
unquote() {
    local value=$1
    value=${value#\'}
    value=${value%\'}
    printf '%s' "$value"
}

readarray -t paths < <(gsettings get "$schema" custom-keybindings | grep -o "'[^']*'" | tr -d "'")
occupied=$(dconf list "$dconf_dir/" 2>/dev/null)

next_free_slot() {
    local index=0 candidate
    while true; do
        candidate="$dconf_dir/custom$index/"
        if [[ " ${paths[*]} " != *" $candidate "* ]] && ! grep -qx "custom$index/" <<<"$occupied"; then
            printf '%s' "$candidate"
            return
        fi
        ((index++))
    done
}

listed=false

for shortcut in "${shortcuts[@]}"; do
    IFS='|' read -r name command binding <<<"$shortcut"

    path=
    for candidate in "${paths[@]}"; do
        if [[ $(unquote "$(gsettings get "$entry_schema:$candidate" name)") == "$name" ]]; then
            path=$candidate
            break
        fi
    done

    if [[ -z $path ]]; then
        path=$(next_free_slot)
        paths+=("$path")
        listed=true
    fi

    gsettings set "$entry_schema:$path" name "$name"
    gsettings set "$entry_schema:$path" command "$command"
    gsettings set "$entry_schema:$path" binding "$binding"

    printf '%s -> %s (%s)\n' "$binding" "$command" "${path%/}"
done

if "$listed"; then
    list=$(printf "'%s'," "${paths[@]}")
    gsettings set "$schema" custom-keybindings "[${list%,}]"
fi
