#!/usr/bin/perl -w

use strict;

use XML::DOM;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);
use Compress::Zlib;
use Time::HiRes;

print "Content-type: text/plain\n\n";

#----------------------------------------
# Parse incoming data
#----------------------------------------
my $buffer;
my %params;

if($ENV{REQUEST_METHOD} eq 'POST')
{
    read(STDIN, $buffer, $ENV{CONTENT_LENGTH});
    $buffer = Compress::Zlib::memGunzip($buffer) if ($ENV{HTTP_X_SATIS_ENCODING} || '') =~ /gzip/; 
    $buffer .= "&";
    $buffer .= $ENV{QUERY_STRING};
} 
else
{
    $buffer = $ENV{QUERY_STRING};
}
my @pairs = split(/&/, $buffer);
my $pair;

foreach $pair(@pairs)
{
    (my $key, my $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%0D%0A/"%0A"/eg;
    $value =~ s/%([A-Fa-f0-9]{2})/pack("C",hex($1))/eg;
    
    if (defined $params{$key})
    {
        $params{$key} .= "\t$value";
    } 
    else
    {
        $params{$key} = $value;
    }
}


my $driver = "mysql";
my $opt_user="";
my $opt_password="";
my $opt_base="";
my $socket="/tmp/mysql.sock"; 
my $appserv="";

my $conf="/usr/local/controller/scripts/scripts.conf";
open(CONF,$conf) or die "Can't open config file!";
my $confparam="";
my $confvalue;

while(<CONF>){
    chomp();
#    print $_ . "\n";
    ($confparam,$confvalue)=split(/=/);
    if(defined($confvalue)){
        if($confparam eq "dbuser") {
            $opt_user=$confvalue;
        }
        elsif($confparam eq "dbpass") {
            $opt_password=$confvalue;
        }
        elsif($confparam eq "db") {
            $opt_base=$confvalue;
        }
        elsif($confparam eq "appserv") {
            $appserv=$confvalue;
        }
        else {}
    }
    else {
        print "WARNING: split didn't find '=' in line.\n";
    }
}
close(CONF);

my $time=sprintf("%.f", Time::HiRes::time*1000);

my $strtoparse = $params{"xml"};
my $parser = new XML::DOM::Parser;
my $indoc = $parser->parse($strtoparse);
my $outdoc = new XML::DOM::Document;

my $messages = $indoc->getElementsByTagName("messages");

if ( $messages->getLength() > 0 )
{
  my $action = "";
  $action = $messages->item(0)->getAttribute("action");

  if ( $action eq "send" )
  {
    $messages->item(0)->setAttribute("time", $time);
    my $message = $messages->item(0)->getElementsByTagName("message");
  }
}

my $xml = $indoc->toString();
$xml =~  s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg;

#Create a request
my $ua= LWP::UserAgent->new;
$ua->agent("ARMchat");

my $connected = 0;
my $try = 0;
my $chatscriptname = "ChatServlet/chatservlet";
my $res_code;
while( !$connected && $try < 5 )
{
  my $req = HTTP::Request->new(POST => "http://$appserv/$chatscriptname");
  $req->content_type('application/x-www-form-urlencoded');
  $req->content("xml=$xml");
  my $res = $ua->request($req);
  $res_code = $res->code;
  if ( $res->is_success )
  {
    $connected = 1;
    print $res->content;
open(FILETEMP, "> filetemp.txt");
print FILETEMP $res->content;
close(FILETEMP);
  }
  $try++;
}

if ( !$connected )
{
  print "<messages><message><![CDATA[&raqua; <i>Error <b>$res_code</b> while connecting to the server (http://$appserv/$chatscriptname).</i><br>]]></message></messages>";
}
