#!/bin/sh

usblp_driver="/sys/bus/usb/drivers/usblp"

inuse=""
if [ -e /sys/bus/usb/devices ]; then
	for usbdev_driver in /sys/bus/usb/devices/*/driver; do
		[ -e "$usbdev_driver" ] || continue
		[ "$(readlink -f "$usbdev_driver")" = "$usblp_driver" ] || continue
		usbdev="${usbdev_driver%/*}"
		inuse="$inuse ${usbdev##*/}"
	done
fi

/usr/lib/sane/saned "$@"
err=$?

for usbdev in $inuse; do
	[ -e "/sys/bus/usb/devices/$usbdev/driver" ] && continue
	logger -t saned "binding device $usbdev back to usblp..."
	printf '%s' "$usbdev" > "$usblp_driver/bind"
done

exit $err
