#!/bin/sh -e

# If multicast addresses have their factory default value, "video_address_*" or
# "audio_address_*", then make addresses out of the six last digits of the
# serial number.

. /etc/init.d/functions.sh

RTP_CONF=/etc/sysconfig/rtp.conf

GROUPS=$(sed -rne 's/NbrOfRTPGroups.*=.*([0-9]+)/\1/p' < $RTP_CONF) || :
[ "$GROUPS" -gt 0 ] ||
	error "Failed to determine the number of RTP parameter groups"

# These two globals are used to return the results from calculate_addresses()
# below.
VIDEO_ADDR=
AUDIO_ADDR=

calculate_addresses()
{
	local group=$1
	local array
	local i=0

	# Multicast addresses must be in the range 239.192.0.0-239.251.254.255.
	local start0=239
	local start1=192
	local range1=60         # 251 - 192 + 1
	local start2=0
	local range2=255        # 254 - 0 + 1
	local start3=0
	local range3=256        # 255 - 0 + 1

	# Get the last six hexadecimal digits from the serial number and
	# turn them into an array of three hexadecimal numbers.
	array=$(bootblocktool -c SERNO 2>/dev/null | \
		sed -nre 's/^......(..)(..)(..)$/0x\1 0x\2 0x\3/p') || :

	[ "$array" ] || error "Failed to read the serial number"

	# Convert the array of hexadecimal numbers to two multicast addresses,
	# one for video and one for audio. The addresses are returned using the
	# global variables $VIDEO_ADDR and $AUDIO_ADDR.
	VIDEO_ADDR=$start0.
	for elem in $array; do
		if [ $i -eq 0 ]; then
			elem=$(($elem + $group * $range1 / $GROUPS))
			VIDEO_ADDR=$VIDEO_ADDR$(($start1 + $elem % $range1)).
		elif [ $i -eq 1 ]; then
			VIDEO_ADDR=$VIDEO_ADDR$(($start2 + $elem % $range2)).
		elif [ $i -eq 2 ]; then
			AUDIO_ADDR=$VIDEO_ADDR$(($start3 + ($elem + $range3 / 2) % $range3))
			VIDEO_ADDR=$VIDEO_ADDR$(($start3 + $elem % $range3))
			return 0
		fi
		i=$(($i + 1))
	done

	return 1
}

init_rtp_addresses()
{
	local group=$1

	# Check if we need to update the configuration file.
	grep -q "\(video\|audio\)_address_$group" $RTP_CONF || return 0

	calculate_addresses $group || return 1

	# Update the configuration file with the calculated addresses.
	sed -i -e "s/video_address_$group/$VIDEO_ADDR/" $RTP_CONF || return 1
	sed -i -e "s/audio_address_$group/$AUDIO_ADDR/" $RTP_CONF || return 1

	information "RTP parameter group $group initialized"

	return 0
}

case "$1" in
	start)
		begin "Determining RTP addresses"
		j=0
		while [ $j -lt $GROUPS ]; do
			init_rtp_addresses $j || break
			j=$(($j + 1))
		done
		# break always returns 0, so we cannot use $? here...
		if [ $j = $GROUPS ]; then
			end 0;
		else
			end 1;
		fi
		;;
	*)
		error "Usage: $0 start"
		;;
esac

exit 0
