#!/bin/bash

# This script can be used to set the appliance volume as a percentage
#
# Usage:
# 
# volume_controller [options] [LEVEL]
#   options: get|set
#   LEVEL: 0-100
# To get the volume of the appliance:
#   volume_controller get
#
# To set the volume of the appliance:
#   volume_controller set [LEVEL]
#   
#   to set the volume at 35%:
#	volume_controller set 35	


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

eeprom_dir=/sys/devices/platform/bone_capemgr
eeprom_status="not found"

show_usage()
{
	echo "Usage:"
	echo ""
	echo " volume_controller [options] [LEVEL]"
	echo "   options: get|set"
	echo "   LEVEL: -42 to 0 dB"
	echo ""
	echo " To get the volume of the appliance:"
	echo "   volume_controller get"
	echo " To set the volume of the appliance:"
	echo "   volume_controller set [LEVEL]"
	echo ""   
	echo "   to set the volume at 35%:"
	echo "	   volume_controller set 35"
}

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
}

for slot in ${eeprom_dir}/slot-*
do
	if [ -d ${slot} ]; then
		read -N 5 val < ${slot}/manufacturer
		if [ "x${val,,*}" == "xbogen" ]; then
			read APPLIANCE_BOARD < ${slot}/board-name
			read APPLIANCE_PART < ${slot}/part-number
			read APPLIANCE_SERIAL < ${slot}/serial-number
			eeprom_status="found"
			break
		fi
	fi
done

if [ $APPLIANCE_PART == "nq-asb" ]; then
  ALSA_OFFSET=150
else
  ALSA_OFFSET=125
fi

VOLUME_CONTROLLER=PCM

NUM_TICKS=2

if [ "$VOLUME_INSTR" == "set" ]; then
	check_num_parameters 2
        NEW_VOLUME_LEVEL=$(($ALSA_OFFSET+($VOLUME_LEVEL * $NUM_TICKS)))
	sudo amixer $VOLUME_INSTR -M $VOLUME_CONTROLLER $NEW_VOLUME_LEVEL > /dev/null
elif [ "$VOLUME_INSTR" == "get" ]; then
	check_num_parameters 1
	V_INFO=$(sudo amixer $VOLUME_INSTR $VOLUME_CONTROLLER)
	L_LINE=$(echo "$V_INFO" | grep "Front Left:")
	R_LINE=$(echo "$V_INFO" | grep "Front Right:")

        HW_LEVEL_L=$(echo $L_LINE | cut -f1 -d"[" | sed 's/Front Left: Playback //g')
        HW_LEVEL_R=$(echo $R_LINE | cut -f1 -d"[" | sed 's/Front Right: Playback //g')

        NEW_V_L=$(($HW_LEVEL_L-$ALSA_OFFSET))
        NEW_V_R=$(($HW_LEVEL_R-$ALSA_OFFSET))
        L_VOL=$(($NEW_V_L / $NUM_TICKS))
        R_VOL=$(($NEW_V_R / $NUM_TICKS))
	
	echo "Left: $L_VOL   Right: $R_VOL"
else
	echo "ERROR: $VOLUME_INSTR is an invalid argument"
	show_usage
fi

