#!/bin/dash
# Description: ALSA Loop sound server (local, bluetooth, network audio)
# jamesbond 2021 - GPLv3

### configuration
CONF=/etc/aloopd.conf
USERCONF=$HOME/.aloopdrc

[ -r $CONF ] && . $CONF
[ -r $USERCONF ] && . $USERCONF # SINK_JOB, SINK_PARAMS, SOURCE_JOB, SOURCE_PARAMS, RESTART_DELAY

RESTART_DELAY=${RESTART_DELAY:-10}
MAXJOBS=${MAXJOBS:-10}

### routines

start() {
	# load snd-aloop if not loaded (this requires ROOT)
	! lsmod | grep -q snd_aloop && modprobe snd-aloop

	if is_up; then
		stop
		echo "Pausing $RESTART_DELAY seconds to make sure all resources are released."
		sleep $RESTART_DELAY
	fi

	# convenience connect to bluetooth speaker if we're supposed to
	[ "$BT_DEV" ] && bt-device -c "$BT_DEV"

	# start jobs	
	for p in $(seq 1 $MAXJOBS); do
		JOB="$(eval echo \$JOB$p)"
		if [ "$JOB" ]; then
			eval $JOB
		else
			break # stop on the first empty job
		fi
	done
	
	echo "aloopd started"
}

stop() {
	# stop it
	is_up && killall alsaloop tx rx bluealsa-aplay 2> /dev/null
	sleep 1

	# if it doesn't die yet, try harder
	is_up && killall -9 alsaloop tx rx bluealsa-aplay 2> /dev/null

	# stop bluetooth connection
	[ "$BT_DEV" ] && bt-device -d "$BT_DEV"

	echo "aloopd stopped"
}

is_up() {
	pidof alsaloop > /dev/null || pidof tx > /dev/null || pidof rx || pidof bluealsa-aplay > /dev/null
}


### main
case "$1" in
	start)          start ;;
	stop)           stop  ;;
	restart|reload) start ;;
	status) is_up && echo "aloopd is running" || echo "aloopd is stopped."
esac
