#!/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 line 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')
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
