#!/usr/bin/perl

use strict;

use Mysql;
use XML::DOM;
use POSIX ":sys_wait_h";
use Time::HiRes;
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

#
#<graphics>
# <time start="..." finish="..." />
# <params>
#  <param id="..." name="..."/>
#  <param id="..." name="..."/>
#  <param id="..." name="..."/>
# </params>
#</graphics>
#
#
#<graphics>
# <params currenttime="...">
#  <param id="..." name="..." paramid="...">
#   <point time="..." status="..." severity="..."><![CDATA[...]]></point>
#   <point time="..." status="..." severity="..."><![CDATA[...]]></point>
#   <point time="..." status="..." severity="..."><![CDATA[...]]></point>
#  </param>
# </params>
#</graphics>

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

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

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

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

my $out_params = $outdoc->createElement("params");
$data->appendChild($out_params);
$out_params->setAttribute("currenttime", $currenttime);

my $params = $indoc->getElementsByTagName("params")->item(0)->getElementsByTagName("param");

my $i;
for ( $i = 0; $i < $params->getLength(); $i++ )
{
  my $param = $params->item($i);
  my $id = $param->getAttribute("id") or "";
  my $name = $param->getAttribute("name") or "";

  my $out_param = $outdoc->createElement("param");
  $out_params->appendChild($out_param);
  $out_param->setAttribute("id", $id);
  $out_param->setAttribute("name", $name) if $name ne "";

  my $query;
  $query = "SELECT ns.NodeID, pd.time, pd.status, pd.value FROM Nodes ns LEFT JOIN SystemConf sc ON ns.NodeID=sc.NodeID LEFT JOIN PollData pd ON sc.NodeID=pd.id WHERE " . ($name eq "" ? "ns.NodeID=$id" : "ns.ParentID=$id AND ns.Name='$name'") . " AND sc.Name='Active' AND sc.Value!=1 AND pd.time > ".($starttime ne "" ? $starttime : $currenttime-86400000)." AND pd.time <= ".($finishtime ne "" ? $finishtime : $currenttime)." ORDER BY pd.time";
  my $sth = Query $dbh $query or die "$Mysql::db_errstr";

  my $paramid = -1;
  my $line;
  while ( $line = $sth->fetchrow_arrayref )
  {
    $paramid    = $$line[0];
    my $time    = $$line[1];
    my $status  = $$line[2];
    my $value   = $$line[3];

    my $point = $outdoc->createElement("point");
    $out_param->appendChild($point);
    $point->setAttribute("time", $time);
    $point->setAttribute("status", $status);
    $point->setAttribute("severity", calculatePollingSeverity($status));
    if ( $value ne "" )
    {
      my $cdata=$outdoc->createCDATASection("cdata");
      $cdata->setData("$value");
      $point->appendChild($cdata);
    }
  }
  undef $sth;
  $out_param->setAttribute("paramid", $paramid) if $name ne "";
  if ( $starttime eq "" )
  {
    my $query = "SELECT name, value FROM SystemConf WHERE NodeID = $paramid";
    my $sth = Query $dbh $query or die "$Mysql::db_errstr";
    my $line;
    my @graph_properties = ("MinLimit", "MaxLimit", "Lowest", "Low", "Normal", "High", "Highest");
    while ( $line = $sth->fetchrow_arrayref )
    {
      foreach my $property (@graph_properties)
      {
        $out_param->setAttribute(lc($property), $$line[1]) if $$line[0] eq $property;
      }
    }
    undef $sth;
  }
}

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

print $final;

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

undef $dbh;

sub calculatePollingSeverity
{
  my $status = shift or 0;
  my $severity = -1;

  if ( $status == -2 ) {
    $severity = 5;
  } elsif ( $status == -1 ) {
    $severity = 5;
  } elsif ( $status == 0 ) {
    $severity = -1;
  } elsif ( $status == 1 ) {
    $severity = 3;
  } elsif ( $status == 2 ) {
    $severity = 4;
  } elsif ( $status == 3 ) {
    $severity = 3;
  } elsif ( $status == 4 ) {
    $severity = 4;
  }

  return $severity;
}

