#!/bin/bash
# 01000-mouse-qemu-tablet.sh
# Prefer QEMU USB Tablet when present

XORG_CONF="$1"

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

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

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

logger -t retrodebian-xorg-autoconfig "Configuring QEMU tablet mouse: $EVENT_DEV"

sed -i \
    -e "s|{InputDeviceDriver}|evdev|g" \
    -e "s|{InputDeviceDevice}|$EVENT_DEV|g" \
    -e "s|{InputDeviceProtocol}|auto|g" \
    "$XORG_CONF" || exit 2

exit 0