#!/bin/bash

# This script can be used to get/set the mixer volume as a percentage
#
# Usage:
# 
# mixer_controller [options] [controller] [LEVEL]
#   options: get|set
#   controller:
#     Router L-1
#     Router L-2
#     Router L-3
#     Router L-4
#     
#   LEVEL: 0-100
# To get the volume of the appliance:
#   volume_controller get
#
# To set the volume of the appliance:
#   mixer_controller set [CONTROLLER] [LEVEL]
#   
#   to mute all channel 1 input from the line output:
#	mixer_controller set "Router L-1" 0	
#   to send channel 4 input to the line output:
#	mixer_controller set "Router L-4" 100	


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

show_usage()
{
	echo "Usage:"
	echo ""
	echo " mixer_controller [options] [controller] [LEVEL]"
	echo "   options: get|set"
	echo "   controller:"
	echo "     Router_L-1"
	echo "     Router_L-2"
	echo "     Router_L-3"
	echo "     Router_L-4"
	echo "   LEVEL: 0-100"
	echo ""
#	echo " To get the volume of the appliance:"
#	echo "   volume_controller get"
	echo " To set the volume of the appliance:"
	echo "   mixer_controller set [CONTROLLER] [LEVEL]"
	echo ""   
	echo "   to mute all channel 1 input from the line output:"
	echo "	   mixer_controller set \"Router L-1\" 0"
	echo "   to send channel 4 input from the line output:"
	echo "	   mixer_controller set \"Router L-4\" 100"
}

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
}

if [ "$VOLUME_INSTR" == "set" ]; then
	check_num_parameters 3
	sudo amixer $VOLUME_INSTR -M "$VOLUME_CONTROLLER" $VOLUME_LEVEL% > /dev/null
elif [ "$VOLUME_INSTR" == "get" ]; then
	check_num_parameters 2
	V_INFO=$(sudo amixer $VOLUME_INSTR -M $VOLUME_CONTROLLER)
	#L_LINE=$(echo "$V_INFO" | grep "Front Left:")
	#R_LINE=$(echo "$V_INFO" | grep "Front Right:")
	
	#L_VOL=$(echo "$L_LINE" | cut -d "[" -f2 | cut -d "]" -f1)
	#R_VOL=$(echo "$R_LINE" | cut -d "[" -f2 | cut -d "]" -f1)
	
	#echo "Left: $L_VOL   Right: $R_VOL"
else
	echo "ERROR: $VOLUME_INSTR is an invalid argument"
	show_usage
fi

