#!/bin/bash

PATH='/sbin:/bin:/usr/sbin:/usr/bin'

if [ -x /usr/bin/logger ]; then
    LOGGER=/usr/bin/logger
elif [ -x /bin/logger ]; then
    LOGGER=/bin/logger
else
    unset LOGGER
fi

# for diagnostics
if [ -t 1 -a -z "$LOGGER" ] || [ ! -e '/dev/log' ]; then
    mesg() {
        echo "$@" >&2
    }
elif [ -t 1 ]; then
    mesg() {
        echo "$@"
        $LOGGER -t "${0##*/}[$$]" "$@"
    }
else
    mesg() {
        $LOGGER -t "${0##*/}[$$]" "$@"
    }
fi

DRIVER=$1
DEVICE_ID=$2

mesg "Device_ID (Driver) - $DEVICE_ID ($DRIVER)"

# Tries to modprobe the driver up to 120 seconds long. This is a "feature" for right after the installation, where DKMS needs some time to compile the driver
# In most cases, this only takes a few seconds. However on a slow machine, this can take some time. 2 min should be plenty however.
### FIXME FIXME FIXME: Scripts run by udev are supposed to be non-blocking. Move the bind methods to the actual install process (pacman/dpkg postinstall hooks)
sleep 0.05                                          # Allows rmmod leetmouse && insmouse leetmouse.ko for local developtment. Sometimes, udev is too fast and modprobes the driver instead of the one we are currently insmodding during development.
if [ ! -d /sys/bus/usb/drivers/"$DRIVER" ] ; then
    mesg "Modprobing $DRIVER"
    i=0
    until [ $i -gt 240 ]; do
        modinfo $DRIVER > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            break
        fi
        sleep 0.5
        ((i=i+1))
    done

    modprobe "$DRIVER"
    sleep 0.05
fi

# Only bind to driver if modprobe worked.
if [ ! -d /sys/bus/usb/drivers/"$DRIVER" ] ; then
    mesg "$DRIVER not loaded. Exiting"
    exit
fi

if [ -d /sys/module/"$DRIVER"/parameters ] && [ -f /sys/module/"$DRIVER"/parameters/no_bind ]; then
    if [ ! $(cat /sys/module/"$DRIVER"/parameters/no_bind) -eq "0" ]; then
        mesg "$DRIVER parameter 'no_bind' set. Exiting"
        exit
    fi
fi

if [ -d /sys/bus/usb/drivers/usbhid/"$DEVICE_ID" ] ; then
    # Unbind from hid
    mesg "Unbinding $DEVICE_ID from hid-generic"
    printf '%s' "$DEVICE_ID" > /sys/bus/usb/drivers/usbhid/unbind
    mesg "Binding $DEVICE_ID to $DRIVER"
    printf '%s' "$DEVICE_ID" > /sys/bus/usb/drivers/"$DRIVER"/bind
    sleep 0.1
    mesg "Finished binding $DEVICE_ID"
fi
