#!/bin/sh

[ "$ACTION" != "remove" ] || exit 0

SANE_GROUP=scanner
grep -q -E "^$SANE_GROUP:" /etc/group || exit 0

grant() {
	echo "hotplug(usb/20-saned): Granting $1 to '$2' for group '$SANE_GROUP'" >/dev/kmsg
	chgrp "$SANE_GROUP" "$2"
	chmod "$1" "$2"
}

usblp_bind="/sys/bus/usb/drivers/usblp/bind"
if [ "$DEVTYPE" = "usb_device" ]; then
	# Filter SANE known devices
	vendor_product="${PRODUCT%/*}"
	vendorid="$(printf '%04x' "0x0${vendor_product%/*}")"
	productid="$(printf '%04x' "0x0${vendor_product#*/}")"
	grep -s -x -F -q "$productid" "/usr/share/sane/$vendorid"-*.usbid || exit 0
	grant g+rw "/dev/$DEVNAME"
elif [ "$DEVTYPE" = "usb_interface" ] && [ "$DRIVER" = 'usblp' ]; then
	# Needed by script /usr/bin/saned to rebind USB devices back to usblp after use
	if [ -e "$usblp_bind" ]; then
		grant g+w "$usblp_bind"
	fi
fi

