#!/bin/bash

# This script is used to control Push-To-Talk behavior using the Nyquist
# Mixer.
#
# Usage:
# 
# mixer_ptt_controller [options] [channel]
#   options: start|stop
#   channel: 1|2|3|4
#     

PTT_OPTION="$1"
PTT_CHANNEL="$2"
paramnum="$#"
ARG_FILE="/var/opt/nyquist/streams/stream.arg"

show_usage()
{
	echo "Usage:"
	echo ""
	echo " mixer_ptt_controller [options] [channel]"
	echo "   options: start|stop"
	echo "   channel: 1|2|3|4"
}

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
}

mute_channels()
{
	for i in {1..4}
	do
		if [ "$i" -ne $PTT_CHANNEL ]; then
			sudo amixer set -M "Router $i-$i" 0%
			#sudo amixer set -M "Router $i-$i" 0% > /dev/null
   			echo "Mute channel $i"
		fi
	done 
}

unmute_all_channels()
{
	for i in {1..4}
	do
		sudo amixer set -M "Router $i-$i" 100%
   		echo "Unmute channel $i"
	done 
	
}

stop_streams()
{
	if pgrep -x "ffmpeg" > /dev/null
	then
    		echo "Audio stream is currently running"
		STREAM_COMMAND=$(cat $ARG_FILE)
	else
    		echo "No audio stream is currently running"
	fi
}

#resume_streams()
#{
#}

check_num_parameters 2

if [ "$PTT_OPTION" == "start" ]; then

	# Is there already audio stream playing on this mixer?
	# If not, only thing to do is mute channels we aren't using
	stop_streams
	mute_channels

	# If so, we need to stop the original 
elif [ "$PTT_OPTION" == "stop" ]; then
	# If there was another audio stream playing, we must resume it

	# Unmute all channels
	unmute_all_channels
else
	echo "ERROR: $PTT_OPTION is an invalid argument"
	show_usage
fi

