#!/usr/bin/perl

use strict;

use Mysql;
use XML::DOM;
use Compress::Zlib;

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

#----------------------------------------
# Parse incoming data
#----------------------------------------
my $buffer;
my %params;
my $cmd = "";

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;
    }
}

#--- Gereral Parameters Definition
my $opt_user="satis";
my $opt_password="satis";
my $opt_base="satis";
my $socket="/tmp/mysql.sock"; 
# Определяем используемый сокет
$ENV{"3306"}="$socket";

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;
	}
	else {}
    }
    else {
#	print "WARNING: split didn't find '=' in line.\n";
    }
}
close(CONF);

#--- Mysql connection 
my $dbh = Mysql->connect("", "$opt_base", "$opt_user", "$opt_password") ||
        die "Can't connect\n";
#--- End of section

#
#<events>
# <time start="..." finish="..." />
# <devices>
#  <id value="..."/>
#  <id value="..."/>
#  <id value="..."/>
# </devices>
# <statuses>
#  <status value="..."/>
#  <status value="..."/>
#  <status value="..."/>
# </statuses>
#</events>
#
#
#<events>
# <time start="..." finish="..." />
#</events>
#
#<events>
# <event id="..." status="..." time="..." raised="..." />
# <event id="..." status="..." time="..." raised="..." />
# <event id="..." status="..." time="..." raised="..." />
#</events>

my $strtoparse = $params{"xml"};
#open(FILE, "> ARMgetEvents.IN.txt");
#print FILE $strtoparse;
#close(FILE);
my $parser = new XML::DOM::Parser;
my $indoc = $parser->parse($strtoparse);

my $starttime = $indoc->getElementsByTagName("time")->item(0)->getAttribute("start") or "";
my $finishtime =  $indoc->getElementsByTagName("time")->item(0)->getAttribute("finish") or "";

my $outdoc = new XML::DOM::Document;
my $data = $outdoc->createElement("events");
$outdoc->appendChild($data);

my $query;
$query = "SELECT id, status, time, raised FROM Alarms WHERE " . ( $starttime ne "" ? ("time >= $starttime " . ( $finishtime ne "" ? "AND time <= $finishtime " : "" ) ) : "" ) . "ORDER BY time DESC LIMIT 1000";
my $sth = Query $dbh $query or die "$Mysql::db_errstr";

my $id;
my $time;
my $status;
my $raised;

my $line;
while ( $line = $sth->fetchrow_arrayref )
{
  $id     = $$line[0] if $$line[0] ne "";
  $status = $$line[1] if $$line[2] ne "";
  $time   = $$line[2] if $$line[1] ne "";
  $raised = $$line[3] if $$line[3] ne "";

  my $event = $outdoc->createElement("event");
  $data->appendChild($event);
  $event->setAttribute("id", $id);
  $event->setAttribute("status", $status);
  $event->setAttribute("time", $time);
  $event->setAttribute("raised", $raised);
}

undef $sth;

#$outdoc->printToFile("ARMOutput.xml");
my $final = $outdoc->toString();
#$final =~  s/([^\w()'*~!.-])/sprintf '%%%02X', ord $1/eg;

print $final;

$outdoc->dispose;
$indoc->dispose;

undef $dbh;
