#!/bin/sh

[ "$ACTION" = add -a "$DEVTYPE" = usb_device ] || exit 0

# Only the FM350 needs this, and running /etc/init.d/fm350-init for every
# usb_device add is expensive: each one sources rc.common, and the first lands
# during preinit while ubus is still coming up.
#
# Gating purely on PRODUCT is not enough. The modem's own uevent is not
# delivered to hotplug on this board (observed on the USB3 bus: the hubs and
# the wifi dongle fire, 0e8d:7127 never does), which is why running on every
# event used to work by accident — some later device's event would arrive and
# the handler would find the modem itself. So match the modem's own event when
# it does come, and otherwise fall back to a presence check.
#
# The check walks sysfs with shell builtins rather than calling lsusb, so the
# common "not the modem, no modem attached" case costs no forks at all.
case "$PRODUCT" in
e8d/7127/*|0e8d/7127/*)
	;;
*)
	# Interface nodes (1-1.3:1.0 and friends) carry no idVendor. Skip them by
	# testing first: a failed redirect is reported by the shell itself, so
	# 2>/dev/null on the read would not suppress it and preinit would get a
	# screenful of "can't open ..." on the console.
	fm350_present=
	for dev in /sys/bus/usb/devices/*/; do
		[ -f "$dev/idVendor" ] || continue
		read -r vid < "$dev/idVendor"
		read -r pid < "$dev/idProduct"
		[ "$vid$pid" = "0e8d7127" ] && { fm350_present=1; break; }
	done
	[ -n "$fm350_present" ] || exit 0
	;;
esac

/etc/init.d/fm350-init start
