#!/usr/bin/sh

# We must clean the HOME environment variable as we don't want SR140 to
# add it's key file to /root/.flexlmrc as the license to use for lmstats
unset HOME

BTCALLD=/usr/sbin/btcalld
BT_CONFIG="ifax/bt/config/btcall.cfg"
BT_FIRMWARE="ifax/bt/firmware"
BT_FLAGS="-l tmp/ecc_trace.txt"
BT_WAIT_POST_FIRMWARE=1
BT_WAIT_POST_BSMI=1

PIDFILE=/var/run/btcalld.pid
SYSTEMD_PIDFILE=/var/run/btcalld-systemd.pid

licence_file_path()
{
    DIR="$1"
    PREFIX="$2"
    SUFFIX="$3"

    FILES=""

    for f in $DIR/$PREFIX*$SUFFIX
    do
	if [ -f $f ]
	then
	    FILES="$FILES:$f"
	fi
    done
    echo "${FILES##:}"
}


BRKTD_LICENSE_FILE=$(licence_file_path /etc/ifax sr140 key)
if [ -n "$BRKTD_LICENSE_FILE" ]
then
	export BRKTD_LICENSE_FILE
fi

# Source HylaFAX EE wrapper
if [ -f /etc/hylafax/wrapper.sh ] ; then
    . /etc/hylafax/wrapper.sh
fi

if [ -f /etc/hylafax/bt-tr1034 ]
then
    . /etc/hylafax/bt-tr1034
fi


if [ -n "$BT_FIRMWARE" ]; then
    # The SR140 memory files can cause license issues if corrupted (by crash?)
    rm -f /dev/shm/sem*SR140*
    echo "Loading Brooktrout TR1034 firmware:"
    $BTCALLD -f $BT_FIRMWARE
    RETVAL=$?
    if [ -n "$BT_WAIT_POST_FIRMWARE" ]; then
	# We need to wait, because otherwise some of the boards aren't ready for ECC
	sleep $BT_WAIT_POST_FIRMWARE
    fi
fi

if [ $RETVAL -eq 0 ] && [ -n "$BT_CONFIG" ]; then
    echo -n "Starting Brooktrout TR1034 BSMI server (btcalld): "
    $BTCALLD -D -c $BT_CONFIG $BT_FLAGS
    RETVAL=$?
    if [ -n "$BT_WAIT_POST_BSMI" ]; then
	sleep $BT_WAIT_POST_BSMI
    fi
    echo ""
fi

sed -n -e '/^[0-9]*$/p' $PIDFILE > $SYSTEMD_PIDFILE

exit $RETVAL

