#!/bin/sh
# 
#  Copyright 2012,2016 Guralp Systems Limited.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#

#
# Arguments:
#  $1: path to serial port device (e.g. "/dev/ttyS1")
#  $2: symbolic port name (e.g. "PortA")
#

PORT="$1"
PORT_NAME="$2"

INITSCRIPT="/etc/init.d/${PORT_NAME}"
if [ ! -x "${INITSCRIPT}" -a -x "/etc/init.local/${PORT_NAME}" ]
then
	INITSCRIPT="/etc/init.local/${PORT_NAME}"
fi


# Some ports (Affinity sensors) are on a multiplexor in which case we need
# to pass the port name through to the autodetector so it can set up the mux.
case "X${PORT_NAME}" in
XSen?Port)	MUX_PORT="${PORT_NAME}" ;;
X*)		MUX_PORT="" ;;
esac


#
# Sanity check: does the serial port actually exist?
#
if [ ! -e "${PORT}" ]
then
	echo "Port device node '${PORT}' does not exist." >&2
	exit 1
fi



#
# Stop the port service if it is running
#
if [ -x "${INITSCRIPT}" ]
then
	"${INITSCRIPT}" stop >& /dev/null
fi



#
# Be really sure nothing is running on the port, or else it will interfere
# with the autodetector.
#
fuser -s -k "${PORT}"
sleep 1
fuser -s -k -KILL "${PORT}"



#
# Try a fast detection.
#
rs232-detect -Xf "${PORT}" $MUX_PORT
[ $? -eq 0 ] && exit 0



#
# Fall back to a slow detection (more time listening at each baud rate).
#
rs232-detect -X "${PORT}" $MUX_PORT
exit 0 # script succeeded, even if it reported no device detected
