#!/bin/bash
# $Id: tty.agent,v 1.11 2004/06/08 12:51:19 hare Exp $
#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
. ./hotplug.subfs.functions
# DEBUG=yes export DEBUG

### Cougar 20040911
killall gpsd

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

#
# generic section
#
### Cougar 20040911
if [ "x${ACTION}" != "xremove" ]; then
for i in 1 2 3 4 5 ; do
    if [ -f /sys$DEVPATH/dev ] ; then
         # work around a race in the block layer,
         # dev is not yet visible
        break
    fi
    mesg TTY "try $i while waiting for $DEVPATH's bus_id $bus_id"
    sleep 1
done
fi

call_udev $1

### Cougar 20040911
# 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 /usr/sbin/hwscan ] && hwscan --cfg=yes $DEVICE
         fi
      fi
### Cougar 20040911
      gpsd -p /dev/ttyUSB0 -s 9600
    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 /usr/sbin/hwscan ] && hwscan --cfg=no $DEVICE
    fi
    ;;
*)
    debug_mesg TTY $ACTION event not supported
    exit 1 ;;
esac