#!/bin/sh

# Wrapper script for picocom.
# Trys to assist the user by adding baudrate information from the standard port
# configuration, and suspending regular serivces that may be running on the
# port.
# Based on the original minicom wrapper script.

CFGSRCDIR=/etc/conf.d/serial

# Only parameter should be the configuration identifier
conf="$1"

# Fast exit if we have more than one argument or it looks like a flag, we
# assume the user already knows what they are doing.
[ $# != 1 -o -z "$conf" -o "${conf:0:1}" = "-" ] \
	&& exec ${0}.bin "$@"

# If the user has given us a name in /dev/ then we need to work back to the
# port name
conf2="$conf"
[ -c "/dev/$conf" ] && conf2=/dev/$conf
if [ -c "$conf2" ]
then
	conf2=$(grep ".*device.*=.*$conf" $CFGSRCDIR/*.cf /dev/null \
		| sed -n -e '1s/.*\/\([^\/]*\)\.cf:.*/\1/p')
else
	conf2=$(echo $conf | tr A-Z a-z | tr -d " ")
	case $conf2 in
	dataout|portdo)	conf2=PortDO	;;
	porta)		conf2=PortA	;;
	portb)		conf2=PortB	;;
	portc)		conf2=PortC	;;
	portd)		conf2=PortD	;;
	porte)		conf2=PortE	;;
	portf)		conf2=PortF	;;
	portg)		conf2=PortG	;;
	portsa1)	conf2=PortSA1	;;
	portsa2)	conf2=PortSA2	;;
	port*)
		echo "Unknown port designation $conf"
		exit 1
		;;
	esac
fi
conf=$CFGSRCDIR/${conf2}.cf

# If we don't have a config file assume the user knows what they are doing and
# simply exec picocom
[ ! -r $conf ] && exec ${0}.bin "$@"

# Grab the baudrate
cf_baud="$(gcs_rwvar gcs_get_varcf baud $conf)"
cf_dev="$(gcs_rwvar gcs_get_varcf device $conf)"


# Now envoke the real picocom suspending any service that may be running
# on the port.
if svc $conf2 status > /dev/null
then
	echo "Suspending service on $conf2"
	if svc $conf2 stop
	then
	    echo "Calling picocom"
	else
	    echo
	    echo "Calling picocom anyway"
	    sleep 2
	fi
	${0}.bin --baud ${cf_baud:-57600} --send-cmd "sx -vv" $cf_dev
	echo "Restarting service on $conf2"
	svc $conf2 start	
else
	exec ${0}.bin --baud ${cf_baud:-57600} --send-cmd "sx -vv" $cf_dev
fi
