#!/bin/dash
# Description: ALSA Loop sound server
# jamesbond 2021 - GPLv3

CONF=/etc/aloopd.conf
USERCONF=$HOME/.aloopdrc
DAEMON=alsaloop
MAX_ATTEMPTS=30
RESTART_DELAY=10

start() {
	local count=$MAX_ATTEMPTS

	# 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

	# starting alsaloop can fail due to resource conflicts
	while ! pidof $DAEMON > /dev/null; do
		if [ -e $USERCONF ]; then
			$DAEMON -g $USERCONF -d
		elif [ -e $CONF ]; then
			$DAEMON -g $CONF -d
		else
			echo "Cannot start $DAEMON - configuration missing."
			return 1
		fi
		
		count=$(( count - 1 ))
		if [ $count -gt 0 ]; then
			sleep 1
		else
			echo "Cannot to start $DAEMON - possibly resource conflicts. Please try again."
			return 1
		fi
	done
	echo "$DAEMON started"
}

stop() {
	# stop it
	is_up && killall alsaloop
	sleep 1
	# if it doesn't die yet, try harder
	is_up && killall -9 alsaloop
	echo "$DAEMON stopped"
}

is_up() {
	pidof $DAEMON > /dev/null
}

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