#!/bin/sh

journalctl _COMM=gnome-shell _UID=$(id -u) -o json --user -n1 -xef |
    #             (.__REALTIME_TIMESTAMP | tonumber) / 1000000 | tostringa
    jq '.__REALTIME_TIMESTAMP + "|" + .MESSAGE' |
    sed -re 's/^"(.*)"$/\1/' |
    grep --line-buffered 'Key repeat discarded' |
    while IFS='|' read ts _; do
        now=$(( $(date +%s) * 1000 * 1000 ))
        elapsed=$(( ${now:-0} - ${ts:-0} ))

        echo "Key repeat discarded ${elapsed}us ago"
        [ "$elapsed" -gt $((3 * 1000 * 1000)) ] && {
            echo "Ignoring past ts, $ts"
            continue
        }

        echo "Detecting key repeat discarded, ts=$ts, throttling"
        gsettings set org.gnome.desktop.peripherals.keyboard repeat false
        sleep 5
        gsettings set org.gnome.desktop.peripherals.keyboard repeat true
        echo "Key repeat throttling ended"
    done
