#!/bin/bash
# Version("2.2.0.0")
# InformationalVersion("2.2.0.0")
# Add music on hold class to asterisk configs
# and reload the configuration

MOHCONFIG=/etc/asterisk/musiconhold_nixxis.conf
SHARES_ROOT=/home/soundsv2share
LOCAL_ROOT=/home/soundsv2
MOH_FOLDER=Moh

function process_moh_add {

	if [[ $QUERY_STRING == "" ]]
	then
		/usr/bin/rsync -r $SHARES_ROOT/$MOH_FOLDER/ $LOCAL_ROOT/$MOH_FOLDER/
	else
#		for f in `ls -A -F $SHARES_ROOT/ | grep "/"`
#		do
#				if [ -d $SHARES_ROOT/$f$QUERY_STRING ]
#				then
#						/usr/bin/rsync -r $SHARES_ROOT/$f$QUERY_STRING/$MOH_FOLDER/ $LOCAL_ROOT/$QUERY_STRING/$MOH_FOLDER
#				fi
#		done
		/usr/bin/rsync -r $SHARES_ROOT/$QUERY_STRING/$MOH_FOLDER/ $LOCAL_ROOT/$QUERY_STRING/$MOH_FOLDER
	fi


	# Trigger class to build the musiconhold_nixxis.conf
	add_moh_class
	
	# Now trigger a reload on Asterisk to activate the new moh config
	asterisk_moh_reload
	
	# Send 200 OK back to appserver
	echo -e "HTTP/1.1 200 OK\r"
	echo -e "Content-Type: text/plain\r"
	echo -e "\r"
	echo -e "\r"
	exit 0
}

function add_moh_class {
	
	# Add warning line and last generation time to beginning of file
	echo -e "; Do NOT edit this file by hand, it is re-generated automatically\r" > $MOHCONFIG
	echo -e "; Last generation at: `date '+%b %d %H:%M:%S'` \r" >> $MOHCONFIG
	
	# Now loop thru the list of subfolders in the MOH location
	for f in `nice -n 19 find $LOCAL_ROOT/$QUERY_STRING/$MOH_FOLDER/* -type d`

	do
		# Extract the name of the subfolder from the full path
		CLASSGUID=`echo $f|awk -F'/' '{ print $NF}'`
		
		# Output class to moh config file
		echo -e "\r" >> $MOHCONFIG
		echo -e "[$CLASSGUID]\r" >> $MOHCONFIG
		echo -e "mode = files\r" >> $MOHCONFIG
		echo -e "directory = $LOCAL_ROOT/$QUERY_STRING/$MOH_FOLDER/$CLASSGUID\r" >> $MOHCONFIG
		echo -e "\r" >> $MOHCONFIG
	done
	

}

function asterisk_moh_reload {
	
	# reloading asterisk MOH classes
	/usr/bin/sudo /usr/sbin/asterisk -rx "moh reload"
	
}


# Main Routine

process_moh_add
exit 0