#!/bin/sh
#flags=notify2|queue|qMergeMess
#name=Text speech
#ico=aSound

#<SnthHgl font="monospace">
# <rule expr="(&quot;(|\\{2}|\\{4}|\\{6}|\\{8})&quot;|&quot;.*[^\\](|\\{2}|\\{4}|\\{6}|\\{8})&quot;)" min="1" color="darkgreen">
#  <rule expr="\\([xX][a-zA-Z0-9]{2}|[0-7]{3}|.{1})" color="green" font_weight="1" />
#  <rule expr="\$\w+" color="green" font_weight="1" />
# </rule>
# <rule expr="#.*$" color="gray" font_italic="1" />
# <rule expr="\b(if|else|elif|then|fi|case|esac|for|do|done|while|using|break|continue|function|shift)\b" color="darkblue" font_weight="1" />
# <rule expr="\b(exit|test|which|sed|echo|rm|mv)\b" color="cyan" font_weight="1" />
# <rule expr="(\$\w+|\$\{.+\}|\$\(.+\))" color="green" font_weight="1" />
# <rule expr="\b(var|in)(?=\s+\w)" color="darkblue" font_weight="1" />
# <rule expr="(\?|\:)" color="darkblue" font_weight="1" />
# <rule expr="\b(0[xX][0-9a-fA-F]*|[0-9]*\.?[0-9]+|[0-9]*\.?[0-9]+[eE][-+]?[0-9]*|true|false)\b" color="darkorange" />
# <rule expr="(\=|\!|\+|\-|\&gt;|\&lt;|\*|\/|\%|\||\&amp;|\^|\~)" color="darkblue" font_weight="1" />
# <rule expr="(\;\;)" color="red" />
# <rule expr="(\;|\,|\{|\}|\[|\]|\(|\))" color="blue" />
#</SnthHgl>

if test $doNtf = 1 -a $en = 1 -a -s $res; then
	play=$(which play)
	if test "x$play" != "x"; then play -q $res; fi

elif test $doRes = 1 -a "x" != "x$mess"; then
	#Specific TTS
	case $lang in
		ru_*)
			iconv=$(which iconv)
			ru_tts=$(which ru_tts)
			sox=$(which sox)
			if test "x$ru_tts" != "x" -a "x$iconv" != "x" -a "x$sox" != "x"; then
				echo "$mess" | $iconv -f $(echo $lang | sed -n "/^[^.]*\.\(.*\)/s//\1/p") -t KOI8-R | $ru_tts -p 0.05 -r 0.4 -s /usr/share/ru_tts/lexicon | $sox -t raw -e signed-integer -b 8 -r 10k -c 1 -v 0.8 - -t wav $res.wav
			fi
		;;
		*) > $res.wav; ;;
	esac

	#Generic TTS for mostly all
	if test ! -s $res.wav; then
		RHVoice=$(which RHVoice-test)
		espeak=$(which espeak)
		text2wave=$(which text2wave)
		if test "x$RHVoice" != "x"; then
			case $lang in
				uk_*) prof="volodymyr"; ;;
				ru_*) prof="aleksandr"; ;;
				en_*) prof="alan"; ;;
				#!!!! Append here need languages and change voices
			esac
			echo $mess > $res.text; $RHVoice -i $res.text -o $res.wav -p $prof
		elif test "x$espeak" != "x"; then
			echo "$mess" | $espeak --stdin -s 130 -v $(echo $lang | sed -n "/\(^[^_]*\).*/s//\1/p") -w $res.wav
		elif test "x$text2wave" != "x"; then
			case $lang in
				uk_*) langFull="ukrainian"; ;;
				ru_*) langFull="russian"; ;;
				en_*) langFull="english"; ;;
				#!!!! Append here need languages
			esac
			echo $mess > $res.text; $text2wave $res.text -o $res.wav -eval "(language_$langFull)"
		fi
	fi

	#Encode before for that less to transfer
	if test -s $res.wav; then
		oggenc=$(which oggenc)
		if test "x$oggenc" != "x"; then oggenc -Q $res.wav -o $res; echo "audio/ogg";
		else mv -f $res.wav $res; echo "audio/wav"; fi
		rm -f $res.wav $res.text
	fi
fi