#!/bin/sh -e

. /etc/init.d/functions.sh
. /etc/conf.d/acd

NAME=acd
DAEMON=/bin/$NAME
DESC="audio configuration daemon"

audio_available_check() {
	local phc="parhandclient --nocgi --nolog"
	local aprop

	# Ignore all parhand error(s)
	aprop=$($phc get Properties.Audio.Audio - RAW) || :
	if [ "$aprop" != yes ]; then
		# Delete unused parameter groups from parhand
		[ ! -e /usr/etc/param/par_audio.conf ] ||
			$phc deletegroup Audio 2>/dev/null || :
		[ ! -e /usr/etc/param/par_audio_source.conf ] ||
			$phc deletegroup AudioSource 2>/dev/null || :

		# Disable audio for trigger data
		$phc set Image.I0.TriggerData.AudioEnabled no 2>/dev/null || :

		information "$DESC $NAME will not be started"
		end 0
		exit 0
	fi
}

start_audio() {
	audio_available_check
	start_daemon $DAEMON $ACD_OPTIONS
}

stop_audio() {
	stop_daemon $DAEMON
}

case "$1" in
	start)
		begin "Starting $DESC"
		start_audio
		end $?
		;;
	stop)
		begin "Stopping $DESC"
		stop_audio
		end $?
		;;
	restart)
		begin "Restarting $DESC"
		# TODO: Do we really need to use sleep?
		stop_audio && sleep 1 && start_audio
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac

exit 0
