#!/bin/bash

# This script can be used to set the appliance stream volume as a percentage
#
# Usage:
# 
# stream_volume_controller [options] [STREAM] [LEVEL]
#   options: get|set
#   LEVEL: 0-100
#   STREAM: the multicast stream to set/get volume
#     supported streams:
#       e_all_call
#       all_call
#       zone_page
#       audio_distribution
#
# To get the volume of the emergency all call stream:
#   stream_volume_controller get e_all_call
#
# To set the volume of the zone_page streams to 15%:
#   stream_volume_controller set zone_page 15


VOLUME_INSTR=$1
STREAM_ID=$2
VOLUME_LEVEL=$3
paramnum="$#"

SC_FILE=/etc/nyquist/stream.config

show_usage()
{
	echo "Usage:"
	echo ""
	echo " stream_volume_controller [options] [STREAM] [LEVEL]"
	echo "   options: get|set"
	echo "   LEVEL: 0-100"
        echo "   STREAM: the multicast stream to set/get volume"
	echo "    supported streams:"
	echo "       e_all_call"
	echo "      all_call"
	echo "      zone_page"
	echo "      audio_distribution"
	echo ""
	echo "To get the volume of the emergency all call stream:"
	echo "  stream_volume_controller get e_all_call"
	echo ""
	echo "To set the volume of the zone_page streams to 15%:"
	echo "  stream_volume_controller set zone_page 15"
}

check_num_parameters()
{
        # Exit if number of parameters are incorrect
        expectedparamnum=$1
        if [ "$paramnum" -ne $expectedparamnum ]; then
		echo "Expected $expectedparamnum arguments - exiting"
		show_usage
                exit 1
        fi
}

STREAM_STRING=NONE

if [ "$STREAM_ID" == "e_all_call" ]; then
	STREAM_STRING=E_ALL_CALL_VOLUME	
elif [ "$STREAM_ID" == "all_call" ]; then
	STREAM_STRING=ALL_CALL_VOLUME	
elif [ "$STREAM_ID" == "zone_page" ]; then
	STREAM_STRING=ZONE_PAGE_VOLUME	
elif [ "$STREAM_ID" == "audio_distribution" ]; then
	STREAM_STRING=AUDIO_DISTRIBUTION_VOLUME
else
	echo "Unknown STREAM $STREAM_ID - exiting"
	show_usage
        exit 1
fi	

if [ "$VOLUME_INSTR" == "set" ]; then
	check_num_parameters 3
	#echo "$STREAM_STRING"
	sudo sed -i "/^$STREAM_STRING/c $STREAM_STRING = $VOLUME_LEVEL" $SC_FILE
elif [ "$VOLUME_INSTR" == "get" ]; then
	check_num_parameters 2
	VOL_STRING=$(awk "/^$STREAM_STRING/{print $NF}" $SC_FILE)	
	echo $(cut -d "=" -f 2 <<< "$VOL_STRING")	
else
	echo "ERROR: $VOLUME_INSTR is an invalid argument"
	show_usage
fi

