#!/bin/bash
startup=""
if [ "$1" == "-s" ]; then
    startup=1
fi
cc=/tmp/$$_cardconfig
cl=/tmp/$$_cardlist
trap "rm -f $cc" 0
if [ -n "$startup" ]; then
    soundcardselect --startup > $cc || exit 1
else
    soundcardselect > $cc || exit 1
fi

identifysoundcards > $cl
primary=`grep '^primary:' $cc`
[ -z "$primary" ] && exit 1
primary=${primary#*:}
backend=${primary%:*}
number=${primary#*:}
args=" -b$backend -dhw:$number -qk -Q/usr/bin/qjackctl "
if grep -q "^latency:auto" $cc; then
    [ ! -f /fervent/bin/ash ] && grep -q "^$primary:pro" $cl && args="$args -L "
elif grep -q "^latency:low" $cc; then
    args="$args -L "
fi
server=`grep '^server:' $cc`
server=${server#*:}
rate=`grep '^samplerate:' $cc`
rate=${rate#*:}
name=`grep "^$primary:" $cl | awk -F: '{ print $7; }'`
module=`grep "^primary:" $cl | awk -F: '{ print $6; }'`
case "$module" in
    *hda*) args="$args -3 "
esac

if [ -z "$startup" ]; then
    troubled=`for p in \`lsof | grep libjack | awk '{ print $2 }'\`; do x=\`cat /proc/$p/cmdline | awk -F'\0' '{ print $1; }'\` ; x=\`basename "$x"\` ; d=\`find /usr/share/applications -name "$x.desktop" -print | head -1 \`; if [ -f "$d" ]; then y=\`grep '^Name=' "$d" | sed 's/^.*=//'\` ; echo "$y ($x)"; else echo $x; fi; done|grep -v knotify|grep -v '^jackd'|grep -v '^rosegardensequencer'|grep -v '^jack-alsa-bridge'`
    if [ -n "$troubled" ]; then
	if ! kdialog --warningcontinuecancel "The following applications are currently using the JACK audio server.\nYou may need to exit or restart these applications before they can continue to play or record audio:\n\n$troubled"; then exit 1; fi
    fi
fi

if [ -n "$server" ]; then
    if [ "`jack-select -t`" != "$server" ]; then
	jack-select -j "$server"
    fi
#    args="$args -j /usr/bin/jackd"
    if [ -x "/usr/bin/$server" ]; then
	args="$args -j /usr/bin/$server"
    fi
fi

if [ -n "$rate" ]; then
    args="$args -r $rate"
fi

if [ -n "$name" ]; then
    echo "Name is: $name"
    name="`echo $name | tr -d '["=]'`"
fi

killall jack-alsa-bridge
if start-qjackctl $args -N "$name"; then
    killall -9 jack-alsa-bridge
    for secondary in `grep '^secondary:' $cc`; do
	secondary=${secondary#*:}
	sbackend=${secondary%:*}
	snumber=${secondary#*:}
	[ "$sbackend" = "alsa" ] || continue
	name=`grep "^$sbackend:$snumber" $cl | awk -F: '{ print $7; }'`
	echo "Name is: $name"
	setsid jack-alsa-bridge -d hw:$snumber -j "$name" -z &
    done
    if grep -q "^startup:synth" $cc; then
        if ! pidof qsynth >/dev/null; then
            c=1
            while ! pidof jackdmp >/dev/null && ! pidof jackd >/dev/null && [ "$c" -lt 20 ]; do
	        sleep 1
	        c=$(($c+1))
	    done
	    sleep 2
	    setsid qsynth --iconic &
	fi
    fi
else 
    kdialog --title Sorry --error " Failed to initialise audio system. \nPlease consult the Studio to Go! documentation for information about supported audio hardware, or contact Fervent Software for support."
fi
