#!/bin/sh

# Finds a device by VendorID and ProductID and sets its persist bit on/off

if [ $# -ne 3 ] || [ ! "$3" = "on" ] && [ ! "$3" = "off" ]
then
	echo "Usage: ${0##/*/} VendorID ProductID on|off"
	exit 1
fi

if [ "$3" = "on" ]
then
	setting=1
else
	setting=0
fi

idvs=`find /sys/devices -name idVendor -exec grep -lx $1 {} \;`

for each_idv in $idvs
do
	this_path=`echo $each_idv | awk '{sub(/idVendor/,"");print}'`
	this_idp=`cat ${this_path}idProduct`
	if [ "$this_idp" = "$2" ]
	then
		found_target=yes
		echo "Found `cat ${this_path}manufacturer`" \
			"`cat \${this_path}product`."
		if 	[ -w "${this_path}power/persist" ]
		then
			echo "Setting persist $3."
			echo $setting > ${this_path}power/persist
		else
			echo "Unable to write to ${this_path}power/persist, aborting."
			exit 1
		fi
	fi
done

if [ ! -n "$found_target" ]
then
	echo "No devices with Product ID \"$1\" and Vendor ID \"$2\" found."
	exit 1
fi

exit 0

