#!/bin/sh
# A minimal stand-in for udevd's database, for libinput/libudev: for every evdev node write
# /run/udev/data/c<major>:<minor> with the ID_INPUT_* tags libinput needs, derived from the
# capability bits the kernel publishes in /sys/class/input/input*/capabilities.
# Only the low 32 bits of a capability word are looked at (all the bits tested here live there).
# No external program runs per device (the first version forked ~30 times per device: `cat`, `readlink` and a $(...) per bit; on a one-CPU
# emulated machine the coldplug took 36 s): everything below is shell builtins (read, test, $(( )), parameter expansion).
SYS=${DESK_UDEV_SYS:-/sys/class/input}
OUT=${DESK_UDEV_OUT:-/run/udev/data}
mkdir -p "$OUT"
# low32 VAR HEXWORD: VAR = the last 8 hex digits of HEXWORD (zero padded)
low32() { w=$2; while [ ${#w} -lt 8 ]; do w=0$w; done; eval "$1=\${w#\${w%????????}}"; }
# cap FILE: first line of a capability file (empty when it does not exist)
cap() { c=; [ -r "$1" ] && read -r c < "$1"; }
here=$PWD
for ev in "$SYS"/event*; do
    [ -e "$ev/dev" ] || continue
    read -r mm < "$ev/dev"                      # "13:64"
    cd -P "$ev/.." 2>/dev/null || continue
    capdir=$PWD/capabilities
    # KEY: words are printed highest first; w0 (keys 0-63) is last, w4 (keys 256-319) is the 5th.
    cap "$capdir/key"; set -- $c
    n=$#
    w0=0; w4=0
    [ $n -ge 1 ] && eval "w0=\${$n}"
    [ $n -ge 5 ] && eval "w4=\${$((n - 4))}"
    low32 w0 "$w0"; low32 w4 "$w4"
    cap "$capdir/rel"; low32 rel "${c:-0}"
    cap "$capdir/abs"; low32 abs "${c:-0}"
    keyboard=0; mouse=0; touch=0
    [ $(( (0x$w0 >> 30) & (0x$w0 >> 28) & 1 )) = 1 ] && keyboard=1                                  # KEY_A and KEY_ENTER
    [ $(( (0x$rel & 3) )) = 3 ] && [ $(( (0x$w4 >> 16) & 1 )) = 1 ] && mouse=1                        # REL_X, REL_Y, BTN_LEFT
    # an absolute pointer with buttons (USB/virtio tablet of QEMU, VirtualBox "USB Tablet", VMware): udev's input_id calls it a mouse
    if [ $(( (0x$abs & 3) )) = 3 ]; then
        if [ $(( (0x$w4 >> 16) & 1 )) = 1 ]; then mouse=1
        elif [ $(( (0x$w4 >> 20) & 1 )) = 1 ]; then touch=1; fi      # BTN_TOUCH and no mouse button: touch screen
    fi
    {
        echo "I:1"
        echo "E:ID_INPUT=1"
        [ $keyboard = 1 ] && { echo "E:ID_INPUT_KEY=1"; echo "E:ID_INPUT_KEYBOARD=1"; }
        [ $mouse = 1 ] && echo "E:ID_INPUT_MOUSE=1"
        [ $touch = 1 ] && echo "E:ID_INPUT_TOUCHSCREEN=1"
        echo "E:ID_SEAT=seat0"
        echo "G:seat"
        echo "Q:seat"
    } > "$OUT/c$mm"
    echo "desk-udev: ${ev##*/} ($mm) keyboard=$keyboard mouse=$mouse touch=$touch"
done
cd "$here"
