#!/bin/sh
#
# tfterm - simple terminal mode for testing TFLINK
#
# Tfterm is a UNIX (Linux) shell program that provides a simple terminal
# with which to test TFLINK.  It first sets the serial port up to the
# default settings for TFLINK - 9600 baud, 8 bits, no parity, 1 stop
# bit, and "raw" data transfer with no echo.
#
# Next, it sets up the controlling TTY to be mostly raw, but with the
# Ctrl-C character set up as the interrupt key.  Once done, it runs two
# programs: a background cat(C) to read data from the serial line and
# display it, and a foreground cat(C) to transfer characters from the
# keyboard to the serial port.  The UNIX cu command is in fact capable
# of most of this.
#
# To exit, enter ^C.  Terminal settings will be restored on normal exit.
#

# definitions
ME=`basename $0`
USAGE="Usage: $ME [ -p device ] [ -b baudrate ]"

# check usage
device="/dev/ttyS1"
baudrate="9600"
while getopts ":p:b:" arg; do
	case "$arg" in
	'p')	device="$OPTARG"
		if [ ! -c $device ]; then
			echo "$ME: $device device file not found" >&2
			exit 1
		fi ;;
	'b')	baudrate="$OPTARG"
		case "$baudrate" in
		'110'|'300'|'600'|'1200'|'2400'|'4800'|'9600'|'19200') ;;
		*)	echo "$ME: unrecognised baud rate $baudrate" >&2
			exit 1 ;;
		esac ;;
	esac
done
shift `expr $OPTIND - 1`
if [ $# -ne 0 ]; then
	echo "$USAGE" >&2
	exit 1
fi

# set up the "TNC" serial line settings
echo "TFTERM test TNC terminal program"
echo "-- setting up terminal line $device, speed $baudrate baud"
stty 1:0:8bd:0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:0:0:0:0:0 <$device
stty $baudrate <$device

# save current terminal line settings
save_stty="`stty -g`"

# set raw terminal, but allow ~ as an interrupt keyA
echo "-- setting up local terminal line"
stty raw -echo isig intr ^C

# start echo (background) and copy (foreground) processes
echo -e "-- connected, press ^C to exit\n"; sleep 1
trap "" 1 2 3 15
cat <$device &
cat >$device

# get here when ^C quit entered - stop echoing
kill -9 $!; sleep 1

# restore saved terminal line settings
stty $save_stty
echo -e "\n-- original terminal settings restored"

# all done
exit 0
