#!/bin/sh
#
# This script is the gpsd udev handler for add/remove events on matched USB
# devices. It expects to see the following environment variables:
#
#    ACTION  = either "add" or "remove"
#    DEVNAME = the full name of the USB device that was just activated
#
# It will accept from /etc/sysconfig/gpsd the following config variables:
#
#    CONTROL_SOCKET = location of the gpsd control socket
#    OPTIONS = options to be passed to gpsd on launch
#
# It hands off to gpsdctl for the actual communication with the daemon.
#
# Do not introduce bashims into this script, as we want it to continue to
# work under Ubuntu.
#
# This file is Copyright 2010 by the GPSD project
# SPDX-License-Identifier: BSD-2-clause

PATH=/usr/sbin:$PATH
export PATH

if [ -r /etc/default/gpsd ]; then
  . /etc/default/gpsd
elif [ -r /etc/conf.d/gpsd ]; then
  . /etc/conf.d/gpsd
elif [ -r /etc/sysconfig/gpsd ]; then
  . /etc/sysconfig/gpsd
  GPSD_OPTIONS=$OPTIONS
  GPSD_SOCKET=$CONTROL_SOCKET
fi

if [ -n "$GPSD_OPTIONS" ]; then
  export GPSD_OPTIONS
fi
if [ -n "$GPSD_SOCKET" ]; then
  export GPSD_SOCKET
fi

if [ -n "$USBAUTO" ]; then
  [ "$USBAUTO" = "true" ] || exit 0
fi

if [ "$ACTION" = "remove" ] ; then
  if echo $DEVLINKS | grep -q /dev/gps; then
    :
  else
    exit 0
  fi
fi

logger -t "gpsd.hotplug" -p daemon.info "$ACTION" "$DEVNAME"

if [ -z "$DEVNAME" ]
then
    logger -t gpsd.hotplug -p daemon.err "no device"
    exit 0
fi

# In recent versions of udev, the gpsd script runs in series with
# the task that creates the real /dev/ttyUSBn device
# node. Unfortunately, the gpsd script runs BEFORE the creation of
# the node, and the node is not created until after you kill the
# gpsd script, because the gpsd script waits forever for the node
# to appear.
#
# This is a race condition, and is best fixed by running the
# actual wait/hotplug portion in the background.

{
    #logger -t gpsd.hotplug -p daemon.info "waiting for" $DEVNAME
    while [ -x $DEVNAME ]
    do
        sleep 1
    done
    #logger -t gpsd.hotplug -p daemon.info $DEVNAME "is active"
    gpsdctl $ACTION $DEVNAME
} &
# vim: set expandtab shiftwidth=4
