#!/bin/sh

usage() {
	(
	echo "Usage: $0 [-sh] <board IP> [board port]"
	echo ""
	echo "If port is not specified, '6666' will be used"
	echo ""
	echo "Options:"
	echo "  -s SADDR   Bind to SADDR on host side"
	echo "  -h         Show this help text and exit"

	[ -z "$*" ] && exit 0
	echo ""
	echo "ERROR: $*"
	exit 1
	) 1>&2
	exit $?
}

if [ "$1" = "--help" ]; then
	usage
fi

while getopts ":hs:" opt; do
	case "$opt" in
		h) usage ;;
		s) saddr="$OPTARG" ;;
		\?) usage "Invalid option -$OPTARG" ;;
		:)  usage "Option -$OPTARG requires an argument" ;;
	esac
done

shift $((OPTIND - 1))

# handle end-of-options marker
if [ "$1" = "--" ]; then
	shift
fi

ip=$1
port=${2:-6666}

if [ -z "${ip}" ] || [ -n "$3" ] ; then
	usage "Invalid number of arguments"
fi

for nc in netcat nc ; do
	type ${nc} >/dev/null 2>&1 && break
done

cleanup() {
	if [ -n "${listener_pid}" ] ; then
		# The listener subshell is its own process group leader (see set -m
		# below); kill the whole group so the netcat child dies with it.
		kill -- -${listener_pid} 2>/dev/null
		wait ${listener_pid} 2>/dev/null
	fi
	stty icanon echo intr ^C
}
trap cleanup EXIT INT QUIT TERM HUP

echo "NOTE: the interrupt signal (normally ^C) has been remapped to ^T"

stty -icanon -echo intr ^T
set -m
(
	while ${nc} ${saddr:+-s "$saddr"} -u -l -p ${port} < /dev/null ; do
		:
	done
) &
listener_pid=$!
set +m

${nc} -u ${ip} ${port}
