#!/usr/bin/env bash
# set all sorts of parameters, start jack and deal with pulseaudio.
# there are 2 different ways to have jack and pa running:
# a) jack runs on the external and pa on the internal card
# b) using pulseaudio-module-jack, pa is bridged into jack
# for case a), it makes sense to use pavucontrol to tell pa to
# leave the external card the fuck alone. (config -> device -> OFF)
# for case b), nothing will use the internal card and you need to connect
# the pulseaudio-sink to your preferred hardware outputs.
# 20210325 wotwot and d0

CARD="LP16"
INPUTS="2"
OUTPUTS="18"

usage() {
	echo "usage: `basename $0` {start|stop|status}"
}

start_stuff(){
	jack_control ds alsa
	jack_control dps device hw:$CARD,0
	# some devices might work with values as low as 64 (2^n values only)
	jack_control dps period 1024
	# USB devices are recommended to be set to 3
	jack_control dps nperiods 3
	jack_control dps rate 44100
	jack_control dps midi-driver seq
	jack_control eps driver alsa
	jack_control eps realtime True
	jack_control eps realtime-priority 85
	jack_control dps inchannels $INPUTS
	jack_control dps outchannels $OUTPUTS
	jack_control start
	jack_control status
	jack_control ep

	pacmd suspend true

	# scenario a)
	pactl unload-module module-jack-sink
	pactl unload-module module-jack-source
	pacmd set-default-sink alsa_output.pci-0000_00_1b.0.analog-stereo
	# scenario b)
	# only enable the sources if you want feedback in the audio system
	#pactl load-module module-jack-sink channels=2
	#pacmd set-default-sink jack_out
	## only enable this if you need pa inputs bridged and if you do, make sure
	## they do not cause feedback loops !
	##pactl load-module module-jack-source channels=2
	##pacmd set-default-source jack_in
	#jack_connect "PulseAudio JACK Sink:front-left" "system:playback_15"
	#jack_connect "PulseAudio JACK Sink:front-right" "system:playback_16"
	#jack_disconnect "PulseAudio JACK Sink:front-left" "system:playback_1"
	#jack_disconnect "PulseAudio JACK Sink:front-right" "system:playback_2"
	pacmd suspend false
}

stop_stuff(){
	jack_control stop

	pacmd suspend true
	SINKID=$(LANG=C pactl list | grep -B 1 "Name: module-jack-sink" | grep Module | sed 's/[^0-9]//g')
	SOURCEID=$(LANG=C pactl list | grep -B 1 "Name: module-jack-source" | grep Module | sed 's/[^0-9]//g')
	if [ ! -z "$SINKID" ] ; then
		pactl unload-module $SINKID
	fi
	if [ ! -z "$SOURCEID" ] ; then
		pactl unload-module $SOURCEID
	fi

	pacmd suspend false
}


case "$1" in
	start)
	start_stuff
	;;
	stop)
	stop_stuff
	;;
	status)
	jack_control status
	;;
	*)
	usage
	;;
esac