#!/bin/bash
# 09900-mouse-proc-handler.sh
# prefer a direct /dev/input/mouseN handler over /dev/input/mice

XORG_CONF="$1"

[ -n "$XORG_CONF" ] || exit 2
[ -f "$XORG_CONF" ] || exit 2
[ -r /proc/bus/input/devices ] || exit 1

MOUSE_DEV="$(awk '
BEGIN { RS=""; FS="\n" }
{
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^H: Handlers=/ && match($i, /mouse[0-9]+/)) {
            print "/dev/input/" substr($i, RSTART, RLENGTH)
            exit
        }
    }
}' /proc/bus/input/devices)"

[ -n "$MOUSE_DEV" ] || exit 1
[ -e "$MOUSE_DEV" ] || exit 1

logger -t retrodebian-xorg-autoconfig "Configuring direct mouse handler fallback: $MOUSE_DEV"

sed -i \
    -e "s|{InputDeviceDriver}|mouse|g" \
    -e "s|{InputDeviceDevice}|$MOUSE_DEV|g" \
    -e "s|{InputDeviceProtocol}|ImPS/2|g" \
    "$XORG_CONF" || exit 2

exit 0