#!/bin/bash
#

args=$*

engine=1
gui=1
quiet=0
verbose=0
jack=0
declare -x JACK_START_SERVER=1
midi=seq
HELP=0
PORT=5028

RATE=44100
DRIVER=-alsa
COUNT=256

LOGO=no

#
# The following is configured by the autotools process.
#
BRISTOL_DIR=/usr/share/bristol

showhelp()
{
	if [ $HELP -eq 2 ]; then
		brighton -V
		exit 0
	fi
	if [ $verbose = 1 ]; then
		# let the bristol gui give a verbose help text.
		engine=0
	else
		brighton -V
		echo
		echo "startBristol [-explorer|-mini|-memory|-hammond|-b3|-dx|-axxe|-odyssey|-2600|-mono|-poly|-juno|-prophet|-pro10|-pro52|-mixer|-vox|-rhodes|-rhodesbass|-obx|-obxa|-aks|<others>] [-oss|-alsa|-jack] [[-help|-h] [-verbose|-v]]"
		echo
		echo "Try 'startBristol -v -h' for more verbose help output on device configuration."
		echo
		echo "Try 'startBristol -b3' or 'startBristol -jack', for example, if you are unsure."
		echo
#		if [ ${EUID} -ne 0 ]; then
#			if [ `ls -l bristol | awk '{printf $3}'` != "root" ]; then
#				echo "You may want to make bristol suid root ownership"
#				echo
#			elif [ ! -u bristol ]; then
#				echo "You may want to make bristol a suid-root executable"
#				echo
#			fi
#		fi
		echo "Q&A to nickycopeland@hotmail.com"
		echo "bugs, features, enhancements to http://sourceforge.net/projects/bristol"
		echo
		exit 0
	fi
}

if [ $# == 0 ]; then
	HELP=1
fi

# Nokey: Don't override BRISTOL if it's not already set
if [ -z "$BRISTOL" ]; then
	if [ -d "${BRISTOL_DIR}/memory" ]; then
		declare -x BRISTOL=${BRISTOL_DIR}
	else
		# We should first take our basename and look for a binary
		BRISTOL=`dirname $0`
		BRISTOL=`dirname $BRISTOL`

		if [ ! -f $BRISTOL/bin/bristol ]; then
			#
			# Take a default
			#
			declare -x BRISTOL=/opt/audio/bristol
		fi
	fi
fi
export BRISTOL
#
# As a note for anybody interested in reading this script, brighton also has
# a BRISTOL_CACHE directory for private memories, sequences and controller maps.
# Default is in $HOME/.bristol and we create this if it is not already made
#
if [ -z "$BRISTOL_CACHE" ]; then
	declare -x BRISTOL_CACHE=${HOME}/.bristol
fi

mkdir -p ${BRISTOL_CACHE}/memory

#
# See if we have an RC file (not currently implemented and should be in the
# BRISTOL_CACHE directory anyway).
#
#if [ -f ${HOME}/.bristolrc ]; then
#	. ${HOME}/.bristolrc
#fi

for index in $*; do
	if [ $index = "-port" ]; then
		shift
		PORT=$1
	fi
	if [ $index = "-summary" ]; then
		brighton -summary
		exit 0
	fi
	if [ $index = "-master" ]; then
		engine=0
	fi
	if [ $index = "-engine" ]; then
		engine=0
	fi
	if [ $index = "-gui" ]; then
		gui=0
	fi
	if [ $index = "-v" ]; then
		verbose=1
	fi
	if [ $index = "--v" ]; then
		verbose=1
	fi
	if [ $index = "-verbose" ]; then
		verbose=1
	fi
	if [ $index = "--verbose" ]; then
		verbose=1
	fi
	if [ $index = "-V" ]; then
		HELP=2
	fi
	if [ $index = "-logo" ]; then
		LOGO=yes
	fi
	if [ $index = "-h" ]; then
		HELP=1
	fi
	if [ $index = "--h" ]; then
		HELP=1
	fi
	if [ $index = "-help" ]; then
		HELP=1
	fi
	if [ $index = "--help" ]; then
		HELP=1
	fi
	if [ $index = "-libtest" ]; then
		engine=0
	fi
	if [ $index = "-quiet" ]; then
		quiet=1
	fi
	if [ $index = "-q" ]; then
		quiet=1
	fi
	if [ $index = "-jack" ]; then
		jack=1
		COUNT=1024
		DRIVER=-jack
	fi
	if [ $index = "-alsa" ]; then
		jack=0
		DRIVER=-alsa
	fi
	if [ $index = "-jackstart" ]; then
		unset JACK_START_SERVER
	fi
	shift
done

# Nokey: Does the BRISTOL directory actually exist?
if [ ! -d $BRISTOL ]; then
	# Apparently not. Let's try to make a guess as to where it is.

	# Try to find out how we were started. If this script was in
	#  the PATH of the user, the $0 should have a leading '/'.
	#  This leading '/' would also be there if this script was
	#  executed as /full/path/name/startBristol
	STARTUP=$0
	# If this script was started as ./"*whatever*" then we need
	#  to strip off the './' in order to accurately determine
	#  the BRISTOL directory
	if [ "$(echo $STARTUP | cut -c 1-2)" = "./" ]; then
		STARTUP=$(echo $STARTUP | cut -c 3-)
	fi
	
	if [ "$(echo $STARTUP | cut -c 1)" = "/" ]; then
		BIN_DIR=$(dirname $STARTUP)
	else
		BIN_DIR=$(dirname $PWD/$STARTUP)
	fi

	declare -x BRISTOL=$(dirname $BIN_DIR)
	unset BIN_DIR STARTUP
fi

#
# Try and get Jack driver information. If the daemon is running, use it. If
# user has a .jackdrc use that, otherwise use /etc/jackdrc
#
if [ ${DRIVER} == "-jack" ]; then 
	JACKPARAMS=`bristoljackstats 2>&1 | awk '/JACKSTATS/'`

	if [ $? == 0 ]; then
		RATE=`echo ${JACKPARAMS} | awk '{print $2}'`
		COUNT=`echo ${JACKPARAMS} | awk '{print $3}'`

		echo jackstats found -rate ${RATE} -count ${COUNT}
	else
		#
		# We should not really get here. If jack was requested but the daemon
		# could not be reached (we did not get feedback from bristoljackstats)
		# then larger issues will occur presently
		#
		# Thanks to Sylvain Robitaille for the next code.
		#
		# See if the process is running
		#
		JACKD=`ps ax | grep -w jackd | grep -vw grep` 

		#
		# Otherwise see what would be started
		#
		if [ -z "${JACKD}" ]; then 
			echo "jack driver requested, jackd not running" 

			if [ -f /etc/jackdrc ]; then
				echo "jack configuration found in /etc/jackdrc"
				JACKD=`cat /etc/jackdrc`
			fi

			if [ -f ~/.jackdrc ]; then
				echo "private jack configuration found in ~/.jackdrc"
				JACKD=`cat ~/.jackdrc`
			fi
		fi

		if [ -z "${JACKD}" ]; then 
			RATE=48000 
			COUNT=1024 
		else
			RATE=`echo ${JACKD} |grep -o -- '-r[0-9][0-9]*' |sed 's/^-r//'` 

			if [ -z "${RATE}" ]; then 
				# assume Jackd's default rate: 
				RATE=48000 
			fi 

			#COUNT=`echo ${JACKD} |grep -o -- '-p[0-9][0-9]*' |sed 's/^-p//'` 
			COUNT=`echo ${JACKD} |grep -o -- '-p[0-9][0-9]*' |tail -n1 |sed 's/^-p//'`

			if [ -z "${COUNT}" ]; then 
				# assume Jackd's default count: 
				COUNT=1024 
			fi 
		fi
	fi
fi

#
# If slabhome already exists, we should take it rather than this definition.
#
declare -x SLAB_HOME=$BRISTOL
declare -x BRIGHTON=$BRISTOL

declare -x LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:${LD_LIBRARY_PATH}:${BRISTOL}/lib

declare PATH=${PATH}:$BRISTOL/bin:/usr/local/bin

if [ ${HELP} -ge 1 ]; then
	showhelp
fi

# see if we should advise making the binary a suid root for FIFO scheduling
#
# This should be dumped, we need to get the RT features integrated.
#
#if [ ${EUID} -ne 0 ]; then
#	if [ `ls -l ${BRISTOL}/bin/bristol | awk '{printf $3}'` != "root" ]; then
#		echo "	You may want to make bristol root ownership"
#	elif [ ! -u ${BRISTOL}/bin/bristol ]; then
#		echo "	You may want to make bristol a suid-root executable"
#	fi
#fi

if [ $jack -eq 1 ]; then
	ldd `which bristol` | grep jack > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo Requested Jack drivers, not compiled into bristol
		exit -1
	fi
fi

if [ ${LOGO} == "yes" ]; then

#
# Just to make sure
#
echo
echo "Bristol is about to start."
echo
echo "This program is totally unrelated to ANY of the companies that produced"
echo "the original instruments emulated by bristol, and none of the original"
echo "manufacturers in ANY way endorse this product."
echo

sleep 1
fi

#
# Requesting an engine. This means we need a free TCP port. Our default is 
# 5028 and if it is not free then search for one from there
#
if [ $engine = 1 ]; then
	echo checking availability of TCP port $PORT
	netstat -taln | grep $PORT > /dev/null
	while [ $? = 0 ]; do
		echo -n "port looked busy, trying "
		PORT=`expr $PORT + 1`
		echo $PORT
		netstat -taln | grep $PORT > /dev/null
	done
	if [ ${PORT} -lt 1024 -a ${UID} -ne 0 ]; then
			echo you may not have permissions for ports less than 1024
	else
		echo using port $PORT
	fi
fi

#
# the bristol engine has flags for -oss or -alsa drivers, -preload buffers of
# -count samples:
#	bristol -preload 4 -count 256 [-oss]
#
if [ $engine = 1 ]; then
	if [ $gui = 1 ]; then
		if [ $quiet = 0 ]; then
			bristol -rate ${RATE} -count ${COUNT} $args -port $PORT &
		else
			bristol -rate ${RATE} -count ${COUNT} $args -port $PORT > /dev/null 2>&1 &
		fi
	else
		if [ $quiet = 0 ]; then
			bristol -rate ${RATE} -count ${COUNT} $args -port $PORT
		else
			bristol -rate ${RATE} -count ${COUNT} $args -port $PORT > /dev/null 2>&1
		fi
	fi
	sleep 1
fi

if [ $gui = 1 ]; then
	if [ $quiet = 0 ]; then
		brighton $args -engine -port ${PORT}
	else
		brighton $args -engine -port ${PORT} > /dev/null 2>&1
	fi
fi

# Make sure we have the children returned, prevents ugly delayed output
if [ $engine = 1 ]; then
	wait % >/dev/null 2>&1
fi
 
