#!/bin/bash
# Shallow frontend for making usb devices sleep and wake up.
# 
# Find out the device's usb id using lsusb or similar -- it looks like
# 5581:0db0.
#
# Then say, e.g.,
#   usbsleep 5581:0db0 off
# to suspend the device, 
#   usbsleep 5581:0db0 on
# to wake it up again.


die() {
	echo $@
	exit 1
}

usage() {
	echo "Usage: $0 <usb id> (on|off)"
	exit 1
}

locateDeviceById() {
# finds the usb devices in the system with the product id $1 and
# calls $2 with all matching sysfs directories.
	productId=$1
	callback=$2
	ls -d /sys/bus/usb/devices/* | \
	while read path
	do
		if [ ! -e $path/idProduct ]; then
			continue
		fi
		id=`cat $path/idVendor`:`cat $path/idProduct`
		if [ "t$productId" == t"$id" ]; then
			$callback $path
		fi
	done
}

wakeUp() {
	echo "Waking up" $1
	echo on > $1/power/control || exit 1
}

putToSleep(){
	echo "Suspending" $1
	echo suspend > $1/power/control || exit 1
}


test ! -z "$1" || usage

devId="$1"
status=$2

if [ "m$status" != mon -a "m$status" != moff ]; then
	die "Status must be "on" or "off", not $status."
fi

if id | grep root 2>&1 > /dev/null
then
	true
else
	exec sudo $0 $*
fi

if [ $status == on ]; then
	locateDeviceById $devId wakeUp
else
	locateDeviceById $devId putToSleep
fi
