#!/bin/sh -e

. /lib/rcscripts/sh/error.sh
. /lib/rcscripts/sh/rc-std2parse.sh

loop_through_channels() {
	# Error messages are left to $setter. Even if $setter fails for some
	# channel, keep trying to start/stop the other channels.
	local mcast_video mcast_audio channel=0
	local setter=/usr/sbin/mcast-always-setter

	case $1 in
		start|stop)
			;
		*)
			error "loop_through_channels: invalid argument '$1'."
			;
	esac

	std2parse /etc/sysconfig/rtp.conf
	while [ $channel -lt $STD2_NETWORK_RTP_NBROFRTPGROUPS ]; do
		eval mcast_video=\$STD2_NETWORK_RTP_R${channel}_ALWAYSMULTICASTVIDEO
		[ "$mcast_video" != yes ] || $setter $1 $channel video || :

		eval mcast_audio=\$STD2_NETWORK_RTP_R${channel}_ALWAYSMULTICASTAUDIO
		[ "$mcast_audio" != yes ] || $setter $1 $channel audio || :

		channel=$(($channel + 1))
	done
}

start_always_multicast() {
	local mca_conf=/etc/dynamic/mcast-always.conf

	# rm cleans any pipeline id if Always Multi. was not properly stopped.
	rm -f $mca_conf ||
		error "start_always_multicast: failed to remove '$mca_conf'."
	loop_through_channels start
}

case $1 in
	start)
		start_always_multicast
		;
	stop)
		loop_through_channels $1
		;
	*)
		error "Usage: $0 {start|stop}"
		;
esac