#!/bin/bash
# Bashism used so don't substitute /bin/sh

# Wrapper script for minicom.
# Trys to assist the user by creating/updating a minicom configuration file for
# the port based on our regular configuration.
# Also attempts to suspend any regular service that may be running on the port.

CFGSRCDIR=/etc/conf.d/serial
CFGDSTDIR=/etc/minicom

# Last parameter should be the configuration identifier
conf="${!#}"

# Fast exit if data-terminal has already done the work for us or no port name
# specified or it looks like a flag
[ $# == 0 -o -z "$conf" -o "$conf" == "data-terminal" -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

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


# Use our config to construct the corresponding minicom config
awk -F "=" '
	BEGIN {
	    port = ""
	    baud = 57600
	}
	{
	    gsub(/ /,"",$1)
	    gsub(/ /,"",$2)
	    if ( $1 == "device" ) port = $2
	    else if ( $1 == "baud" ) baud = $2
	}
	END {
	    printf "pr port             %s\n", port
	    printf "pu baudrate         %d\n", baud
	    printf "pu bits             8\n"
	    printf "pu parity           N\n"
	    printf "pu stopbits         1\n"
	    printf "pu minit\n"
	    printf "pu mreset\n"
	    printf "pu rtscts           No\n"
	}
' < $CFGSRCDIR/${conf2}.cf > $CFGDSTDIR/minirc.$conf

# Now envoke the real minicom 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 minicom"
	else
	    echo
	    echo "Calling minicom anyway"
	    sleep 2
	fi
	${0}.bin -w $@
	echo "Restarting service on $conf2"
	svc $conf2 start	
else
	exec ${0}.bin -w $@
fi
