#!/bin/bash
# $Id: 50-visor.dev 262 2004-08-09 12:22:13Z hare $
#set -x
#
# tty hotplug policy agent for Linux kernels
#
# Kernel TTY hotplug params include:
#	
#	ACTION=%s [add or remove]
#	DEVPATH=%s
#

cd /etc/hotplug
. ./hotplug.functions
# DEBUG=yes export DEBUG

# Should match definitions in /etc/hotplug/hotplug.subfs.functions
DESKTOPDIR=/var/lib/Desktop
TEMPLATEDIR=/usr/share/hotplug/DesktopTemplates

if [ "$DEVPATH" = "" ]; then
    mesg Bad TTY invocation: \$DEVPATH is not set
    exit 1
fi

if [ ! -L /sys$DEVPATH/device ] ; then
	exit 0
fi

#
# do the real action
#
export DEVICE=/dev/${DEVPATH##*/}

case $ACTION in
add)
    mesg "add tty device $DEVPATH"
    #
    # special handling for visor/palm devices
    #
    if [ -e /etc/hotplug/usb/desktopdev ]; then
      if [ -e /sys/bus/usb-serial/drivers/visor/"${DEVPATH##*/}" ]; then
         /etc/hotplug/usb/desktopdev 
	 # TOFIX: We can handle only one Palm at the same time atm
	 # TOFIX: yes, yes, this is broken, but tell me something better for all 
         #        different Palms. ttyUSB0 can come after ttyUSB1 ...
	 D=$DESKTOPDIR/kpilot.desktop
	 EXISTING="-1"
	 [ -e $D ] && EXISTING=`sed -n -e 's,^Dev=/dev/ttyUSB\(.*\),\1,p' $D`
	 if [ "$EXISTING" -lt "${DEVICE#/dev/ttyUSB}" ]; then
	    # remove first to generate a new create event via DNOTIFY
	    [ -e $D ] && rm -f $D
            sed s,__DEVICE__,"${DEVICE}", $TEMPLATEDIR/kpilot.desktop \
                > $D
	    [ -e /sbin/hwscan ] && /sbin/hwscan --cfg=yes $DEVNAME
         fi
      fi
    fi
    ;;

remove)
    mesg "remove tty device $DEVPATH"
    if [ -e $DESKTOPDIR/kpilot.desktop ]; then
       grep -q ^Dev=${DEVICE}$ $DESKTOPDIR/kpilot.desktop && \
            rm -f $DESKTOPDIR/kpilot.desktop
	[ -e /sbin/hwscan ] && /sbin/hwscan --cfg=no $DEVICE
    fi
    ;;
*)
    debug_mesg TTY $ACTION event not supported
    exit 1 ;;
esac
