#!/bin/bash

# Exit on error
set -e

DRIVER=leetmouse
DRIVER_PATH=/sys/bus/usb/drivers/$DRIVER

# No argument has been passed over. Exit
if [ $# -eq 0 ]; then
    exit
fi

# ########## Code below is ran only, if the leetmouse kernel module has been loaded successfully

# Leetmouse is not loaded. Exit
if [ ! -d $DRIVER_PATH ] ; then
    exit
fi

# Find all devices, which are currenlty bount to leetmouse and unbind them (+ rebind to usbhid)
# Note: Only works, if the udev rules are disabled. This manage function is mainly used for the uninstall process
if [ $1 = "unbind_all" ]; then
    # Temporarily disable binding via udev to leetmouse
    printf '%s' "1" > /sys/module/leetmouse/parameters/no_bind

    for d in $DRIVER_PATH/*/ ; do
        # Strip basepath and trailing/leading slashes
        d=${d#$DRIVER_PATH}
        d="${d#?}"; d="${d%?}"

        if [ $d != "module" ]; then
            printf '%s' "$d" > /sys/bus/usb/drivers/leetmouse/unbind
            printf '%s' "$d" > /sys/bus/usb/drivers/usbhid/bind
        fi
    done

    # Reenable binding to leetmouse via udev after all pointer devices successfully have attached to usbhid again
    sleep 2
    printf '%s' "0" > /sys/module/leetmouse/parameters/no_bind
fi

# Triggers a udev refresh so it binds all pointer devices to leetmouse
if [ $1 = "bind_all" ]; then
    udevadm control --reload-rules
    udevadm trigger --subsystem-match=usb --subsystem-match=input --subsystem-match=hid --attr-match=bInterfaceClass=03 --attr-match=bInterfaceSubClass=01 --attr-match=bInterfaceProtocol=02
fi
