#!/bin/sh
# geninitrd mod: usbkbd

find_modules_usbkbd() {
	verbose "Finding USB keyboard modules"

	if [ "$(echo /sys/class/input/input*)" = "/sys/class/input/input*" ]; then
		return
	fi

	local modules i module bInterfaceClass bInterfaceProtocol

	for i in /sys/bus/usb/devices/*-*:*; do
		# standard usb keyboards
		if [ -f $i/bInterfaceClass -a -f $i/bInterfaceProtocol ]; then
			bInterfaceClass=$(cat $i/bInterfaceClass)
			bInterfaceProtocol=$(cat $i/bInterfaceProtocol)
			if [ "$bInterfaceClass" = "03" -a "$bInterfaceProtocol" = "01" ]; then
				module=$(readlink $i/driver/module)
				module=$(basename $module)

				if [ -n "$module" ]; then
					verbose "Found USB Keyboard driver: $module"
					modules="$modules $module"
				fi
			fi
		fi
	done

	for i in /sys/class/input/input*; do
		# standard usb keyboards
		if [ -f $i/device/bInterfaceClass -a -f $i/device/bInterfaceProtocol ]; then
			bInterfaceClass=$(cat $i/device/bInterfaceClass)
			bInterfaceProtocol=$(cat $i/device/bInterfaceProtocol)
			if [ "$bInterfaceClass" = "03" -a "$bInterfaceProtocol" = "01" ]; then
				module=$(readlink $i/device/driver/module)
				module=$(basename $module)

				if [ -n "$module" ]; then
					verbose "Found USB Keyboard: $(cat $i/name)"
					modules="$modules $module"
				fi
			fi
		fi

		# logitech unifying receiver (unfortunately I know no way to detect keyboard only)
		if grep -qi "Logitech Unifying Device" $i/name; then
			module=$(readlink $i/device/driver/module)
			module=$(basename $module)

			if [ -n "$module" ]; then
				verbose "Found USB Logitech Unifying Device: $(cat $i/name)"
				modules="$modules $module"
			fi
		fi
	done

	if [ -n "$modules" ]; then
		# usb controllers
		if is_kmod; then
			# find parent devices of usb hubs
			for hub_dc in `grep -l 09 /sys/bus/usb/devices/*/bDeviceClass`; do
				ctrl=$(dirname $(dirname $(readlink -f $hub_dc)))
				if [ -f "$ctrl/modalias" ]; then
					find_module $(cat "$ctrl/modalias")
					usb_ctrl_found=1
				fi
			done
		fi
		if [ -z "$usb_ctrl_found" ]; then
			# fallback to old pci only method
			for m in $(find_modules_by_class "0c03"); do
				find_module "$m"
			done
		fi

		# always add hid-generic
		find_module "-hid-generic"

		for m in $modules; do
			find_module "-$m"
		done
	fi
}
