#!/bin/bash # make sure we have the required udev variables if [ -z "$BUSNUM" -o -z "$DEVNUM" -o -z "$DEVPATH" ]; then exit 1 fi declare -rg _vboxdir="/usr/lib/virtualbox" declare -rg _vboxmanage="${_vboxdir}/VBoxManage" declare -rg _vboxruntime="${_vboxdir}/VirtualBox" declare -r user="$(ps aux | grep "$_vboxruntime" | grep -v grep | awk '{print $1}')" if [ -z "$user" ] || ! id "$user" &> /dev/null; then # No user session with virtualbox is running, exit silently exit 0 fi export VBOX_IPC_SOCKETID="$user" # set default locale to make sure the vboxmanage output is not broken on UTF-8 chars [ -s "/etc/default/locale" ] && . /etc/default/locale [ -z "LANG" ] && LANG="de_DE.UTF-8" export LANG # make sure LC_ALL does not fiddle with this unset LC_ALL # find UUID of running VM declare -r vmuuid="$("$_vboxmanage" list runningvms | awk '{print $NF}' | tr -d '{}')" if [ -z "$vmuuid" ]; then logger "Failed to find running VirtualBox instance of '$user'." exit 1 fi declare -r devname="/dev/vboxusb/$BUSNUM/$DEVNUM" for tts in 1 1 1 1 1 2 3 5 STOP; do if [ "x$tts" = "xSTOP" ]; then logger "$0: Could not find '$devname' as expected..." exit 1 fi [ -e "$devname" ] && break logger "waiting for $devname..." sleep $tts done declare -r usbaddress="$("$_vboxmanage" list usbhost | grep "$DEVPATH" | awk '$1 = /Address:/ {print $2}')" logger "Attaching '$usbaddress' to '$vmuuid'..." for tries in 1 2 3 STOP; do if [ "$tries" = "STOP" ]; then logger "$0: Failed after 3 tries!" exit 1 fi if "$_vboxmanage" controlvm "$vmuuid" usbattach "$usbaddress"; then exit 0 fi sleep 1 done