#!/bin/sh
# Use the existing OpenWrt loader for USB peripherals and their class devices.
# Match device aliases, never a vendor list or the complete module inventory.

valid_alias() {
	case "$1" in
		*[[:space:]]*) return 1 ;;
		usb:?*|hid:?*|scsi:?*) return 0 ;;
		*) return 1 ;;
	esac
}

if [ "$#" -eq 1 ] && [ "$1" = '--coldplug' ]; then
	set --
	# USB interfaces often have a modalias but no dev attribute, so procd's
	# device-node coldplug alone does not replay all driver discovery events.
	for path in /sys/bus/usb/devices/*/modalias \
		/sys/bus/hid/devices/*/modalias /sys/bus/scsi/devices/*/modalias; do
		[ -r "$path" ] || continue
		alias=
		IFS= read -r alias < "$path" || [ -n "$alias" ] || continue
		valid_alias "$alias" || continue
		set -- "$@" "$alias"
	done
	[ "$#" -gt 0 ] || exit 0
	# Unknown optional hardware must not fail boot. Dependency resolution,
	# module options and blacklists remain the stock loader's responsibility.
	/sbin/modprobe -a -b -q "$@" || :
else
	[ "$#" -eq 1 ] || exit 2
	valid_alias "$1" || exit 0
	exec /sbin/modprobe -b -q "$1"
fi
