#!/bin/bash
# This file is distributed as part of the bit-babbler package.
# Copyright 2015 - 2017,  Ron <ron@debian.org>
#
# Example libvirt QEMU hook for cold-plugging BitBabbler devices into
# newly started virtual machines.  To use this, it must be installed
# as /etc/libvirt/hooks/qemu (or wherever the equivalent configuration
# is found on your system), and then libvirtd must be restarted if you
# did not previously have a 'qemu' hook installed there.  It does not
# need to be restarted again if you modify an existing script there.
#
# This script assumes that you have the udev rules from the bit-babbler
# package installed and active, and that you have bbvirt(1) configured
# to assign devices to the guest domains you want them available in.
#
# It will use the device assignments from /etc/bit-babbler/vm.conf to
# trigger cold plug events for each device that should be made available
# in the guest VM that is being started (which will in turn signal the
# bbvirt helper script to actually attach them to that guest).

. /etc/bit-babbler/vm.conf

guest_name=$1
operation=$2


# The path where udevadm is found was Helpfully changed by systemd from the
# original location in /sbin to now be in /bin.  Since we can't be certain
# what will be in the PATH when this is called, and since we still need to
# support systems prior to that change, that means we need to search for it
# ourselves.  If we can't find it in any of the expected places, then fall
# back to assuming the user's system really does have it in their PATH.
# If that's not true, this will fail out soon enough when we try to use it.
UDEVADM="udevadm"
for f in /bin/udevadm /sbin/udevadm; do
    if [ -x "$f" ]; then
        UDEVADM=$f
        break;
    fi
done


if [ "$operation" = "started" ]; then
    devices="DOMAIN_RNG_${guest_name}[@]"
    opts=( -c change -s usb -a "idVendor=0403" -a "idProduct=7840" )

    for d in "${!devices}"; do
        "$UDEVADM" trigger "${opts[@]}" -a "serial=$d"
    done
fi

# Always return success here, we don't want to abort guest operations.
exit 0

# vi:sts=4:sw=4:et:foldmethod=marker
