#!/bin/bash

MSG="$@"
if test -z "$TTSLANG"; then
	TTSLANG=ko
fi

if test -z "$MSG"; then
	echo $0 "<message to speak>"
	exit 1
fi

MD5STR=$(echo $MSG | ( md5sum || md5 ) 2>/dev/null | awk '{print $1}')
if test -n "$MD5STR"; then
	SOUND_FILE="/tmp/sound-$TTSLANG-$MD5STR.mp3"
else
	SOUND_FILE="/tmp/sound-$TTSLANG-$(echo $MSG | tr -d ' ').mp3"
fi

if which mpg123 >/dev/null 2>&1; then
	PLAYER=mpg123
elif which afplay >/dev/null 2>&1; then
	PLAYER=afplay
else
	echo "No mp3 player (e.g.: mpg123, afplay)"
	exit 1
fi
{
	if test ! -f "$SOUND_FILE"; then
		if wget -Z -q -O $SOUND_FILE --user-agent="Mozilla/5.0 (X11; U; Linux i686; en-US)" --referer="http://www.gstatic.com/translate/sound_player2.swf" "http://translate.google.com/translate_tts?q=$MSG&tl=$TTSLANG" 2>/dev/null
		then
			:
		elif curl -q -o $SOUND_FILE --user-agent "Mozilla/5.0 (X11; U; Linux i686; en-US)" --referer "http://www.gstatic.com/translate/sound_player2.swf" "http://translate.google.com/translate_tts" --data q="$MSG" --data tl="$TTSLANG" 2>/dev/null
		then
			:
		else
			echo "Sound download failed"
		fi
	fi
	$PLAYER $SOUND_FILE >/dev/null 2>&1
} &
