#!/bin/bash

# AUTOR: Luis Moreno Rodriguez          2010


function translate () {
	if [ $# = 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
		echo -e "Fetch translation from google. Usage 'translate text' or 'translate world'"
		return
	fi
	local TEMP_FILE="/tmp/deleteme.$$"

	if [ $# -gt 1 ]; then
		local IS_WORD="false"
	else
		local IS_WORD="true"
	fi

	echo "********************************************************"
	echo " Choose the direction to translate '$*'"
	echo "********************************************************"
	echo " 0 - spanish to english"
	echo " 1 - english to spanish"
	echo " [Other] EXIT"
	echo "********************************************************"
	echo -n "Enter your menu choice: "
	read OPTION
	echo

	local SRC=en
	local DST=es
	case $OPTION in
		0)       SRC=es; DST=en;;
		1)       SRC=en; DST=es;;
		*)       echo "Exit"; return;;
	esac
	local LNG=`echo "$LANG" | cut -d '_' -f 1`
	local CHARSET=`echo $LANG | cut -d '.' -f 2` #usefull if charset is unicode

	if [ "$IS_WORD" = "true" ]; then
		lynx -accept_all_cookies -dump -hiddenlinks=ignore -nonumbers -assume_charset=$CHARSET -display_charset=$CHARSET "http://www.google.com/dictionary?aq=f&langpair=${SRC}|${DST}&q=${1}&hl=$LNG"| grep -C 2 -A 5 -w "*" > /$TEMP_FILE

		if [ ! -s $TEMP_FILE ]; then
			echo "No translation for '$1'"
		else
			cat $TEMP_FILE
		fi
		rm -f $TEMP_FILE
	else
		wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$@&langpair=${SRC}|${DST}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/';
	fi
}


translate_world $*


