#!/bin/sh
#############################################################
# This script sends random data to serial ports in physical order
#############################################################
path="${0%/*}"
. "$path/inc/gwhw.inc"

usage() {
	die 'gwhw serial [CMD] [PORT]'
}

TASK="${1:-list}"; shift
COM="${1:-.*}"; shift
COM="${COM//[cC]}"

doTask=list
case "$TASK" in
	blink) doTask=blink
	;;
	list)  doTask=list
	;;
	status)  doTask=listStatus
	;;
	*) usage
esac
#############################################################

blink() {
	while read id f; do
		ttypath="$(ls -1 "$f" 2>/dev/null | grep -- 'tty' | sed 's;^tty;/dev/tty;g')"
		if [ -c "${ttypath}" ]; then
			printf "%500s" | tr " " "R" > "${ttypath}"
		fi
	done
}

list() {
	while read id f; do
		ttypath="$(ls -1 "$f" 2>/dev/null | grep -- 'tty' | sed 's;^tty;/dev/tty;g')"
		# Serial ports are not regular files
		[ -f "${ttypath}" ] && ttypath="${ttypath:+${ttypath} (regular file!)}"
		printf "%-4s %-20s\n" "C${id}" "${ttypath:-Not found!}"
	done
}

getFuser() {
	[ -c "$1" ] || return
	fuser -s "$1" && echo "in use" || echo "unused"
}

getStty() {
	[ -c "$1" ] || return
	stty -F "$1" -g
}

listStatus() {
	while read id f; do
		ttypath="$(ls -1 "$f" 2>/dev/null | grep -- 'tty' | sed 's;^tty;/dev/tty;g')"
		# Serial ports are not regular files
		[ -f "${ttypath}" ] && ttypath="${ttypath:+${ttypath} (regular file!)}"
		printf "%-4s %-20s %-10s %s\n" "C${id}" "${ttypath:-Not found!}" "$(getFuser "${ttypath}")" "$(getStty "${ttypath}")"
	done
}

#############################################################

hw="/usr/local/etc/telem/hw-run.xml"
awk '/<Port .*index="'"${COM}"'" .*\/>/{split($2,a,"\"");split($5,b,"\"");print a[2],b[2]}' "$hw" | $doTask

