#!/bin/bash
# $Id: libusbscanner,v 1.2 2004/08/26 10:26:08 twaugh Exp $
#
# /etc/hotplug/usb/libusbscanner
#
# Sets up newly plugged in USB scanner so that the user who owns
# the console according to pam_console can access it from user space
#
# Note that for this script to work, you'll need all of the following:
# a) a line in the file /etc/hotplug/usermap that corresponds to the 
#    camera you are using.
# b) a setup using pam_console creates the respective lock files
#    containing the name of the respective user. You can check for that
#    by executing "echo `cat /var/{run,lock}/console.lock`" and 
#    verifying the appropriate user is mentioned somewhere there.
# c) a Linux kernel supporting hotplug and usbdevfs
# d) the hotplug package (http://linux-hotplug.sourceforge.net/)
#
# In the usermap file, the first field "usb module" should be named 
# "libusbscanner" like this script.
# 

if [ -z "${DEVICE}" ]
then
    exit 0
fi

DEVDIR=/dev
DEVNAME="scanner-usb-$(echo ${DEVICE#../proc/bus/usb/} | sed -e 's;/;:;g')"

wait_and_add () {
    local limit=90
    # wait until the action can be performed but no longer
    # than $limit seconds
    while ! ln -snf "${DEVICE}" "${DEVDIR}/${DEVNAME}" ; do
	    [ "$limit" = 0 ] && return
	    sleep 1
	    limit=$((limit - 1))
    done
    
    /sbin/pam_console_apply "${DEVDIR}/${DEVNAME}"
}

if [ "${ACTION}" = "add" ] && [ -f "${DEVICE}" ]
then

    # Make a symlink from /dev/scanner-usb-BBB:DDD to /proc/bus/usb/BBB/DDD.
    # If /etc/security/console.perms is set up properly, pam_console will
    # follow the symlink and set the permissions of /proc/bus/usb/BBB/DDD such
    # that "console" users will be able to use their USB scanner.
    #
    # If the scanner is "cold plugged", and this event will occurred before
    # the root filesystem was writeable, then we wait in a background
    # until a link in ${DEVDIR} can be created.  Permissions on
    # /proc/bus/usb/BBB/DDD will be of a "revert" type; see
    # man 5 console.perms.  This is fine; when a device does not exist
    # at all we do not particularly care about its permissions.
    #
    ( wait_and_add >/dev/null 2>&1 & )
    
    # See /etc/hotplug/usb.agent for a description of how REMOVER works.
    ln -sf "${0}" "${REMOVER}"
fi

if [ "${ACTION}" = "remove" ]
then
    rm -f "${DEVDIR}/${DEVNAME}"
fi
