#!/usr/bin/perl

use strict;

use DBI;
use XML::DOM;
require "../scripts/connect.pl";

close(STDERR);

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

if ($ENV{REQUEST_METHOD} eq 'POST') {
    read(STDIN, $buffer, $ENV{CONTENT_LENGTH});
    $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 $commit = 0; 

if (defined $params{"commit"}) {
    $commit = $params{"commit"};
} 

my $isAlarm = 0;
my $line;

my $dbh = satisMysqlConnect();

my $query = "UPDATE PollData SET sync = 0 WHERE sync = 1;";
if ($commit == 1) {
    $query = "UPDATE PollData SET sync = -1 WHERE sync = 1;";
}
$dbh->do("$query");

my $doc = new XML::DOM::Document;
my $xml=$doc->createElement("xml");
$doc->appendChild($xml);
my $poll;
my $set;
my $unset;

$query = "UPDATE PollData SET sync=1 WHERE sync = 0 LIMIT 10000;";
$dbh->do("$query");

$query = "SELECT time,id,value,status FROM PollData where sync = 1;";
my $sth = $dbh->prepare($query) || die "Can't prepare: $query\n";
$sth->execute();
while ($line = $sth->fetchrow_arrayref) {
    $poll=$doc->createElement("poll");
    $xml->appendChild($poll);
    $poll->setAttribute("time","$$line[0]");
    $poll->setAttribute("node","$$line[1]");
    if($$line[2] ne "") {
		$$line[2] =~ s/[^ :\-\+,\.a-zA-Z0-9\/]*//g;
		$poll->setAttribute("value","$$line[2]");
    }
    $poll->setAttribute("status","$$line[3]");
}
$sth->finish();

$dbh->disconnect();
my $res = $doc->toString();
$doc->dispose();
print "Content-type: text/plain\n";
print "X-Satis-Length: " . length($res) . "\n\n";
print $res;
