#! /bin/bash
# vim: set tabstop=4 shiftwidth=4 noexpandtab filetype=sh:

# usbgetty.sh - a2cloud script to start a getty on a USB serial devie (to be replaced.)
#
# To the extent possible under law, T. Joseph Carter and Ivan Drucker have
# waived all copyright and related or neighboring rights to the a2cloud
# scripts themselves.  Software used or installed by these scripts is subject
# to other licenses.  This work is published from the United States.

ttyUSB=

pkill -f "sleep 86399"

if [[ $(grep -e '-scanttyUSB' <<< "$*") ]]; then
	# called with -scantty isntead of device name?

	# if upper USB port
	if [[ -c /dev/ttyUSBupper ]]; then
		ttyUSB=ttyUSBupper

	# if hub in upper port, use highest numbered port on hub
	elif [[ $(ls -1 /dev/ttyUSBupper_hub* 2> /dev/null | wc -l) -gt 0 ]]; then
		ttyUSB=$(ls -1 /dev/ttyUSBupper_hub* 2> /dev/null | tail -1 | cut -c 6-)

	# if hub in lower port with multiple adapters, use highest numbered port on hub
	elif [[ $(ls -1 /dev/ttyUSBlower_hub* 2> /dev/null | wc -l) -gt 1 ]]; then
		ttyUSB=$(ls -1 /dev/ttyUSBlower_hub* 2> /dev/null | tail -1 | cut -c 6-)

	# no port found eligible for getty
	else
		sleep 86399
	fi

elif [[ $(grep -o 'ttyUSB[^ ]*' <<< "$*") ]]; then
	# if specified USB device name is found
	ttyUSB=$(grep -o 'ttyUSB[^ ]*' <<< "$*")
else
	sleep 86399
fi

if [[ -c /dev/$ttyUSB && ! $(ps aux | grep "[g]etty.*$ttyUSB") ]]; then
	# if adapter seems to exist and doesn't already have a getty,
	#   kill all USB gettys and start the getty, otherwise do nothing
	pkill -f "/sbin/getty.*ttyUSB"
	exec /sbin/getty $(sed "s/-scanttyUSB/$ttyUSB/" <<< "$@");
else
	sleep 86399
fi
