#!/bin/sh -e
# NAME=USB presence
# DESCRIPTION=Tests the presence of designated USB devices. It checks for a count of USB devices that match specified idVendor and idProduct and gives a success if they're equal to COUNT parameter or failure if they're not.
# DESTROYS_HDD=false
# IS_INTERACTIVE=false
# POWEROFF_DURING_TEST=false
# VERSION=0.1
# TAGS=usb
# DEPENDS=USB
# VAR=IDVENDOR:string:0403:Filter in only devices with this idVendor (match all if empty, could be an extended regular expression)
# VAR=IDPRODUCT:string:6001:Filter in only devices with this idProduct (match all if empty, could be an extended regular expression)
# VAR=COUNT:int:1:There should be this many devices

. _inq-config-global; . $SHARE_DIR/functions-test

get_usb_devices()
{
	for I in /sys/bus/usb/devices/*; do
		# Check that it's readable
		[ -r "$I/idVendor" ] || continue
		[ -r "$I/idProduct" ] || continue

		# Match
		if [ -n "$IDVENDOR" ]; then
			if ! cat $I/idVendor | egrep -q "$IDVENDOR"; then
				continue
			fi
		fi
		if [ -n "$IDPRODUCT" ]; then
			if ! cat $I/idProduct | egrep -q "$IDPRODUCT"; then
				continue
			fi
		fi

		echo $I
	done
}

FOUND=`get_usb_devices | wc -l`

[ "$FOUND" -eq "$COUNT" ] && test_succeeded || 
	test_failed "Found $FOUND devices instead of $COUNT"
