#!/bin/sh
# Hack to keep my keyboard layout sane.
: <<'EOF'

Every time my USB keyboard crashes and reboots, it gets a default
keymap.  There's probably some way to fix this, but this is a
workaround.  My custom keymap puts parentheses on the unshifted {}
keys to the right of QWERTYUIOP:

    key <AD11> {
        type[group2]= "FOUR_LEVEL",
        symbols[Group1]= [       parenleft,       braceleft ],
        symbols[Group2]= [      dead_acute,  dead_diaeresis,  dead_diaeresis,  dead_abovering ]
    };
    key <AD12> {
        type[group2]= "FOUR_LEVEL",
        symbols[Group1]= [      parenright,      braceright ],
        symbols[Group2]= [            plus,        asterisk,      asciitilde,     dead_macron ]
    };

It relegates the [] more commonly found there, but much less often
used, to the shifted 9 and 0 keys:

    key <AE09> {
        type[group2]= "FOUR_LEVEL",
        symbols[Group1]= [               9,       bracketleft ],
        symbols[Group2]= [               9,      parenright,    bracketright,       plusminus ]
    };
    key <AE10> {
        type[group2]= "FOUR_LEVEL",
        symbols[Group1]= [               0,      bracketright ],
        symbols[Group2]= [               0,           equal,      braceright,          degree ]
    };

So this program checks every five seconds to see if we have reverted
to the bad standard layout and, if so, sets the good layout.

EOF

log() {
    echo "$(date) $*" >&2
}

xkbfile="${1:-$HOME/dev3/server-0-after-options-hacked.xkb}"

if [ ! -f "$xkbfile" ]; then
    echo "Cannot find keyboard file '$xkbfile'" >&2
    exit 1
fi

if [ ! -n "$DISPLAY" ]; then
    echo "DISPLAY not set; is X-Windows not running?" >&2
    exit 2
fi

log "Starting with '$DISPLAY' and '$xkbfile'"
trap 'log "Shutting down"' 0
trap 'log "Control-C"; exit 0' 2

okay=false

while : ; do
    if xkbcomp "$DISPLAY" - | grep -q '9.*bracketleft'; then
        if ! "$okay"; then
            log "Keyboard seems okay"
            okay=true
        fi
    else
        log "Keyboard got fucked up, fixing"
        xkbcomp "$xkbfile" "$DISPLAY"
        okay=false
    fi
    sleep 5
done
