#!/bin/bash
# Melchior FRANZ <melchior.franz@ginzinger.com>, Public Domain
#
# Usage: terminal [<serial-device> [<transfer-rate> [<stty-arguments ...>]]]
#        quit by typing Ctrl-A followed by x within 0.5 s

dev=${1:-/dev/ttyS0} && shift
baud=${1:-115200} && shift

restore_serial=$(stty -F $dev -g) || exit
restore_console=$(stty -g)
[ -t 1 ] && [ "$TERM" != "dumb" ] && begin="\e[90m" && end="\e[m"

terminate() {
	echo -e "$end"
	exec &>/dev/null
	kill %cat
	stty -F $dev $restore_serial
	stty $restore_console
	exit 0
}
trap terminate EXIT HUP INT QUIT PIPE TERM

stty -F $dev $baud min 1 time 0 nl0 cr0 tab0 bs0 vt0 ff0 \
	-parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts \
	-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr \
	-icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8 -opost -olcuc \
	-ocrnl -onlcr -onocr -onlret -ofill -ofdel -isig -icanon -iexten \
	-echo -echoe -echok -echonl -noflsh -xcase -tostop -echoprt \
	-echoctl -echoke "$@"

stty -echo intr ^- quit ^- erase ^- kill ^- eof ^- eol ^- eol2 ^- swtch ^- \
	start ^- stop ^- susp ^- rprnt ^- werase ^- lnext ^- flush ^-

echo -e "$begin{${0##*/} -- $(date +"%Y/%m/%d %H:%M:%S") -- ^A-x to quit}$end\n"
cat $dev&

while IFS= read -n1 c; do
	case "$c" in
	"")
		echo >$dev -ne "\r"
		;;
	)
		read -N1 -t0.5 key
		[ "$key" == 'x' ] && break
		echo >$dev -ne "$key"
		;;
	*)
		echo >$dev -ne "$c"
		;;
	esac
done
