#!/bin/bash
#
# Jack quickstart script
#
# Copyright  (C) 2014 Manu Kebab <io.gnu.linux@free.fr>
#
#------------------------------------------------------


PROGNAME=${0##*/}

set -a
source gettext.sh
set +a
export TEXTDOMAIN="${PROGNAME}"
export TEXTDOMAINDIR="/usr/share/locale"
. /usr/bin/gettext.sh

TITLE="~ Jack Restart ~"

set -x

# Display a usage message.
usage()
{
	cat <<EOF

Usage: $PROGNAME { -s | --start-jack }
       $PROGNAME { -h | --help }

This program facilite Jack2 and Ladish startup and offers some specific
arguments to check, kill, start and restart jack and ladish stuff.

Options:
    -h, --help                     display this usage message and exit
    -k, --kill-jack                kill jack and ladish stuff
    -l, --load-studio              load ladish studio
    -s, --start-jack               start jack and ladish stuff
    -r, --restart-jack             restart all
        
EOF
}


init()
{
	# Ensure config file is OK
	[ ! -e ~/.config/io-studio.conf ] && cp /etc/io-studio.conf ~/.config/io-studio.conf

	for arg in `cat /etc/io-studio.conf | grep "=\"" | cut -d \= -f 1`
	do
		if ! cat ~/.config/io-studio.conf | grep ${arg}
		then
			cat /etc/io-studio.conf | grep ${arg} >> ~/.config/io-studio.conf
		fi
	done

	# Check for first run...
	if [ ! -d ~/.config/jack ]
	then
		jack_control ds alsa
		parse_conf
		jack_control dps rate ${RATE}
		jack_control dps period ${PERIOD}
		jack_control dps nperiods ${NPERIOD}
		jack_control ips audioadapter device ${HW_ID}
		jack_control ips audioadapter rate ${RATE}
		jack_control ips audioadapter periodsize ${PERIOD}
		jack_control ips audioadapter nperiods ${NPERIOD}
		jack_control eps realtime-priority 95
	fi
	jack_control status | grep stopped && jack_control start
	sleep 1

	[ ! -d ~/.ladish/studios ] && mkdir -p ~/.ladish/studios
	[ ! -e ~/.ladish/studios/DefaultAlsa.xml ] && cp /etc/skel/.ladish/studios/DefaultAlsa.xml ~/.ladish/studios/

	# Check if jack is already configured, otherwise reset parameters to default.
	alternate_rate

	if [ ! -n "${SOUNDCARD}" ]
	then
		jack_configure
	fi

	# Check if the soundcard in jack conf is physically available, otherwise launch jack configuration
	CONFIG_HW=$(cat ~/.config/jack/conf.xml | grep device -m 1 | awk '{print $2}' | cut -d '<' -f1 | cut -d ':' -f2)

	if [ ! -n "${STUDIO}" ]
	then
		sed -i 's/STUDIO.*/STUDIO\=\"DefaultAlsa\"/g' ~/.config/io-studio.conf
		parse_conf
	fi

	if ! cat /proc/asound/cards | grep ${CONFIG_HW}
	then
		sed -i 's/HW_ID.*/HW_ID\=\"\"/g' ~/.config/io-studio.conf
		sed -i 's/SOUNDCARD.*/SOUNDCARD\=\"\"/g' ~/.config/io-studio.conf
		jack_configure -sc1
		jack_configure &
		exit 0
	fi
}


parse_conf()
{
	# Parse default conf
	. /etc/io-studio.conf

	# Parse user conf
	[ -e ~/.config/io-studio.conf ] && . ~/.config/io-studio.conf
}


alternate_rate()
{
	parse_conf

	if [ "${RATE}" -eq 48000 ]
	then
		ALTERNATE_RATE="44100"
	else
		ALTERNATE_RATE="48000"
	fi
}


kill_jack()
{
	echo "I: Kill jack"
	killall -s SIGKILL pnmixer > /dev/null 2>&1
	pulseaudio -k > /dev/null 2>&1
	pulseaudio -k > /dev/null 2>&1
	killall -s SIGKILL pulseaudio > /dev/null 2>&1
	killall a2j a2jmidid alsa_in alsa_out jmcore ladiconfd gladish ladishd jack-aloop-daemon jack-pulse-daemon jack-zbridge-daemon jackd jackdbus start-pulseaudio-x11 > /dev/null 2>&1
	killall -s SIGKILL ladi-system-tray > /dev/null 2>&1
	killall -s SIGKILL ladi-system-tray > /dev/null 2>&1
	killall -s SIGKILL jackd > /dev/null 2>&1
	jack_control exit > /dev/null 2>&1
	killall -s SIGKILL jackdbus > /dev/null 2>&1
}


kill_loop()
{
	echo "I: Kill loop"
	killall -s SIGKILL pnmixer > /dev/null 2>&1
	pulseaudio -k > /dev/null 2>&1
	pulseaudio -k > /dev/null 2>&1
	killall -s SIGKILL pulseaudio > /dev/null 2>&1
	killall alsa_in alsa_out jack-aloop-daemon jack-pulse-daemon jack-zbridge-daemon start-pulseaudio-x11 > /dev/null 2>&1
}


start_jack()
{
	echo "I: Start jack... should be renamed"
	if [ "${SOUNDSERVER}" = "Jack+AlsaLoop" ] || [ "${SOUNDSERVER}" = "Jack+ZitaBridge" ]
	then
		if ! grep -qs "\[Loopback" /proc/asound/cards
		then
			diag_error_module
			exit 0
		fi
	fi
}


load_studio()
{
	echo "I: Load and start ${STUDIO} studio"
	if ladish_control slist | grep "${STUDIO}"
	then
		ladish_control sload "${STUDIO}" > /dev/null 2>&1
		ladish_control sstart > /dev/null 2>&1
	else
		ladish_control sload DefaultAlsa > /dev/null 2>&1
		ladish_control sstart > /dev/null 2>&1
	fi
}


start_studio()
{
	alternate_rate

	if [ "${SOUNDSERVER}" = "Jack+AlsaLoop" ]
	then
		jack_configure --set-jack-alsa-loop
		jack-aloop-daemon &
		gladi_tray
		#pnmix_tray

	elif [ "${SOUNDSERVER}" = "Jack+ZitaBridge" ]
	then
		jack_configure --set-jack-zita-bridge
		jack-zbridge-daemon &
		gladi_tray
		#pnmix_tray

	elif [ "${SOUNDSERVER}" = "Jack+PulseAudio" ]
	then
		jack_configure --set-jack-pulseaudio
		jack-pulse-daemon &
		gladi_tray
		#pnmix_tray

	elif [ "${SOUNDSERVER}" = "Alsa" ] || [ "${SOUNDSERVER}" = "PulseAudio" ]
	then
		kill_jack
		[ "${SOUNDSERVER}" = "Alsa" ] && jack_configure --set-alsa

		if [ "${SOUNDSERVER}" = "PulseAudio" ]
		then
			jack_configure --set-pulseaudio
			pulseaudio --start
		fi
		pnmix_tray
	fi
	exit 0
}


stop_studio()
{
	echo "I: Stop ladish studio"
	if ladish_control sisloaded | grep yes
	then
		ladish_control sstop
		ladish_control sunload
	fi
}


running_check()
{
	echo "I: Running check..."
	if ladish_control sisloaded | grep -qs yes && jack_control status | grep -qs started && jack_lsp | grep -qsv "JACK server not running"
	then
		echo "I: Jack and ladish OK"
		JACK_LADISH="on"
		load_studio
		start_studio
		exit 0
	else
		echo "E: Jack and ladish sick"
		JACK_LADISH="off"
	fi
}


gladi_tray()
{
	if [ -x /usr/bin/ladi-system-tray ] && ! ps -ef | grep ladi-system-tray | grep -v grep
	then
		ladi-system-tray > /dev/null 2>&1 &
	fi
	if [ "${GLADISH_RUN}" = "TRUE" ] && [ -x /usr/bin/gladish ] && ! ps -ef | grep gladish | grep -v grep
	then
		gladish > /dev/null 2>&1 &
	fi
}


pnmix_tray()
{
	if [ -x /usr/bin/pnmixer ] && ! ps -ef | grep pnmixer | grep -v grep
	then
		pnmixer > /dev/null 2>&1 &
	fi
}


check_up()
{
	if [ "${SOUNDSERVER}" = "Jack+AlsaLoop" ] || [ "${SOUNDSERVER}" = "Jack+ZitaBridge" ] || [ "${SOUNDSERVER}" = "Jack+PulseAudio" ]
	then
		kill_loop
		#start_studio
		load_studio
		sleep 2
		running_check
		if [ "${JACK_LADISH}" = "off" ]
		then
			kill_jack
			jack_configure -sc2
			#start_studio
			load_studio
			sleep 2
			running_check
			if [ "${JACK_LADISH}" = "off" ]
			then
				kill_jack
				jack_configure -sc3
				#start_studio
				load_studio
				sleep 2
				running_check
				if [ "${JACK_LADISH}" = "off" ]
				then
					kill_jack
					jack_configure -sc4
					#start_studio
					load_studio
					sleep 2
					running_check
					if [ "${JACK_LADISH}" = "off" ]
					then
						kill_jack
						jack_configure -sc5
						#start_studio
						load_studio
						sleep 1
						running_check
						if [ "${JACK_LADISH}" = "off" ]
						then
							cat /proc/asound/cards | grep ']:' | grep -v Loopback \
								| sed  -r -e 's/^ *//g' -e 's/\[//g' -e 's/\]//g' -e 's/  //g' \
									-e 's/ :/:/g' -e 's/: /:'"${TAB}"'/g' > /tmp/soundcards-info

							AUDIO_CARDS=$(cat /tmp/soundcards-info | wc -l)

							if [ "${AUDIO_CARDS}" -lt 2 ]
							then
								kill_jack
								diag_error_jack
								jack_configure --set-alsa
								exit 0
							else
								sleep 0.5
								yad --title "${TITLE}" \
									--image=/usr/share/icons/Gant/64x64/status/dialog-warning.png \
									--window-icon=jack-quickstart \
									--buttons-layout=center \
									--text-align=center \
									--text="$(eval_gettext $'  Problem starting Jack...  \\n\\n  Try another soundcard?  ')"
								ret=$?

								if [ "${ret}" -eq 1 ]
								then
									diag_error_jack
									jack_configure --set-conf1
									jack_configure --set-alsa
									exit 0
								else
									jack_configure -sc1
									jack_configure -cs &
									exit 0
								fi
							fi
						fi
					fi
				fi
			fi
		fi
	elif [ "${SOUNDSERVER}" = "Alsa" ] || [ "${SOUNDSERVER}" = "PulseAudio" ]
	then
		start_studio
	fi
}


diag_error_jack()
{
	sleep 0.5
	yad --title "${TITLE}" \
		--image=/usr/share/icons/Gant/64x64/status/dialog-error.png \
		--window-icon=jack-quickstart \
		--button=gtk-ok:0 \
		--buttons-layout=center \
		--text-align=center \
		--text="$(eval_gettext $'  An error occured, Jack will be disabled...  \\n\\n  You can try to reconfigure it with the program:  \\n<b>Jack Configure</b>  ')"
}


diag_error_module()
{
	sleep 0.5
	yad --title "${TITLE}" \
		--image=/usr/share/icons/Gant/64x64/status/dialog-error.png \
		--window-icon=jack-quickstart \
		--button=gtk-ok:0 \
		--buttons-layout=center \
		--selectable-labels \
		--text-align=center \
		--text="$(eval_gettext $'  Error, module snd-aloop is not loaded...  \\n\\n  Add: "snd-aloop" without quotes to /etc/modules and reboot,  \\n\\n  You can load it manually with the command:  \\n  sudo modprobe snd-aloop')"
}



# Validate arguments.
case "$1" in
	-h|--help)
		usage
		exit 0
		;;
	-k|--kill-jack)
		kill_jack
		;;
	-l|--load-studio)
		kill_loop
		start_studio
		;;
	-s|--start-jack)
		init
		running_check
		start_jack
		check_up
		;;
	-r|--restart-jack)
		init
		kill_jack
		start_jack
		check_up
		;;
	*)
		running_check
		init
		kill_jack
		start_jack
		check_up
		;;
esac


exit 0
