#!/bin/sh

_me=$(basename $0)
_xml="/tmp/${_me}.$PPID"

die() {
	echo $@
	[ -f ${_xml} ] && rm ${_xml}
	exit 1
}

usage() {
	echo "Usage: ${_me} <vm-name> <bus-no dev-no | vendor-id:device-id>"
}

case ${_me} in
	uattach*)
		_subcmd="attach"
		;;
	udetach*)
		_subcmd="detach"
		;;
	*)
		die "${_me}: I can not identify myself."
		;;
esac
		
make_xml() {
	echo "<hostdev mode='subsystem' type='usb' managed='yes'>" > ${_xml}
	case $# in
		1)
			local _numcolons=$(echo $1 | grep -o ":" | wc -l)
			[ ${_numcolons} -eq 1 ] || die "${_me}: malformed vendor-id:device-id argument"
			local _vendor=$(echo $1 | sed 's/\:.*//')
			local _product=$(echo $1 | sed 's/.*\://')
			printf "\t<source>\n\t\t<vendor id='0x%s'/>\n\t\t<product id='0x%s'/>\n\t</source>\n" \
				${_vendor} ${_product} >> ${_xml}
			;;
		2)
			printf "\t<source>\n\t\t<address bus='%s' device='%s'/>\n\t</source>\n" $1 $2 >> ${_xml}
			;;
		*)
			die "Oops!"
			;;
	esac
	echo "</hostdev>" >> ${_xml}
}

case $# in
	2)
		make_xml $2
		;;
	3)
		make_xml $2 $3
		;;
	*)
		die $(usage)
		;;
esac

virsh list --name | grep "^$1$" > /dev/null 2>&1 || die "${_me}: virtual machine \"$1\" is not running."

virsh ${_subcmd}-device $1 ${_xml}

rm ${_xml}
