#!/bin/sh

##
## This script is invoked by udev rules whenever USB device appears or
## changes. This happens in usbvm domain (or dom0 if USB controller
## drivers are in dom0). The script records information about available
## USB devices into XS directory, making it available to qvm-usb tool
## running in dom0.
##

# FIXME: Ignore USB hubs and other wierd devices (see also in udev-usb-remove).
[ "`echo $TYPE | cut -f1 -d/`" = "9" ] && exit 0
[ "$DEVTYPE" != "usb_device" ] && exit 0

# qubesdb doesn't allow dot in key name
XSNAME=`basename ${DEVPATH} | tr . _`

# in general ID_SERIAL = "${ID_VENDOR}_${ID_MODEL}_${ID_SERIAL_SHORT}"
DESC="${ID_VENDOR_ID}:${ID_MODEL_ID} ${ID_VENDOR_ENC} ${ID_MODEL_ENC} ${ID_SERIAL_SHORT}"

VERSION=`cat /sys/$DEVPATH/version | tr -d ' '|cut -f 1 -d .`

# ignore usbip-connected devices, as most likely already passed through from
# another VM
if echo $DEVPATH | grep -q /vhci_hcd; then
    exit 0
fi

QDB_KEY="/qubes-usb-devices/$XSNAME"

# The last one is meant to trigger watches
qubesdb-write \
    "$QDB_KEY/desc" "$DESC" \
    "$QDB_KEY/usb-ver" "$VERSION" \
    "$QDB_KEY/interfaces" "$ID_USB_INTERFACES" \
    /qubes-usb-devices ''

# Make sure PVUSB backend driver is loaded.
/sbin/modprobe xen-usbback 2> /dev/null || true
