#!/usr/local/bin/perl -w
# Script to translate a string to another language using
# Google Translate
# Author: Michael Landin <mich@freebsdcluster.org>
# Version 1.20
#
# Use: ./translate -f<from language> -t<to language> text


=head1 NAME

translate - translates a string via Google Translate

=head1 SYNOPSIS

    translate B<-f> I<country-code> B<-t> I<country-code> 'string'

=head1 DESCRIPTION

    Translate will take a word or a string and translate to another language
    using Google Translate.

=head1 OPTIONS

=over 4

=item -f 

    Language that we should translate from. You can use the following: 
    en (English), fr (French), de (German), it (Italien), es (Spanish), pt (Portugeese).

=item -t

    Language we should translate the word/string to. Same language codes as above.

=item -h

    Displays the help screen.

=back

=head1 CHANGELOG

    January 2018:
    o Switch from Babelfish to Google Translate
    March 2003:
    o Add MAN page
    o Fix new babelfish semantics
    June 2002:
    o Initial release

=head1 BUGS

    Sometimes a translated string coming back from Google may contain special characters 
    (e.g. accents etc on fx. french words) which causes the screen to garble up.

=head1 AUTHOR

    Written by Michael Landin <mich@freebsdcluster.org>

=cut

use LWP::UserAgent;
use Getopt::Std;
use HTTP::Request::Common;
use URI::Escape;

# check paramaters
    getopts('hf:t:');
    if (defined($opt_h)) {
	print "translate version 1.20
    by Michael Landin <mich\@freebsdcluster.org>
    Usage : translate -f<from language code> -t<to language code> text
    Note : If more than one word needs to be translated, string must be 
    single-quoted.

    Language codes available :
    English - en
    French - fr
    German - de
    Italien - it
    Portuguese - pt
    Spanish - es

    Example : translate -f en -t fr 'how are you' will give the result :
    [how are you] --> comment allez vous
translate -h $opt_h will produce this help message\n";
    exit;
} elsif(!(@ARGV) || !(defined($opt_t)) || !(defined($opt_f))) {
    print "Please specify languages - and text\nUsage: translate -f<from language code> -t<to language code> text\nSee translate -h for help\n";
    exit;
}


# send request
my $from_lang = $opt_f;
my $to_lang = $opt_t;
my $convert_text = uri_escape($ARGV[0]);
my $url = "http://translate.googleapis.com/translate_a/single?client=gtx&dt=t&q="
    . $convert_text
    . "&sl="
    . $from_lang
    . "&tl="
    . $to_lang;


my $ua = LWP::UserAgent->new();
$ua->agent('Mozilla/5.0');

#print $url."\n";

$resp = $ua->get($url);

if ($resp->is_success) {
 $newstr = $resp->content;
 @fields = split(/"/, $newstr);
 print "[$ARGV[0]] ---> $fields[1]\n";
} else { 
    print "Program failed with message: ", $resp->status_line;
}

