#!/usr/bin/perl

use strict;

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

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

my $ua= LWP::UserAgent->new;
$ua->agent("ARMconnection");

#----------------------------------------
# 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

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

my $tasks = $indoc->getElementsByTagName("task");
my $i;

TASK: for ( $i = 0; $i < $tasks->getLength(); $i++ )
{
  my $task = $tasks->item($i);
  my $id = $task->getAttribute("id");
  next TASK if $id eq "";

  my $query;
  $query = "SELECT ns.Type, sc.Name, sc.Value FROM Nodes ns JOIN SystemConf sc ON sc.NodeID=ns.NodeID WHERE ns.NodeID=$id";
  my $sth = Query $dbh $query or die "$Mysql::db_errstr";

  my $new_type = "";
  my $new_name = "";
  my $new_value = "";

  my $new_device = $indoc->createElement("device");

  my $line;
  while ( $line = $sth->fetchrow_arrayref )
  {
    $new_type  = $$line[0];
    $new_name  = $$line[1];
    $new_value = $$line[2];

    my $new_parameter = $indoc->createElement("parameter");
    $new_device->appendChild($new_parameter);
    $new_parameter->setAttribute("name", $new_name);

    my $new_text = $indoc->createTextNode("text");
    $new_text->setData($new_value);
    $new_parameter->appendChild($new_text);
  }

  if ( $new_type ne "" )
  {
    $new_device->setAttribute("type", $new_type);
    $task->appendChild($new_device);
  }

  $query = "SELECT ns.Type, sc.Name, sc.Value FROM Nodes ns1 JOIN Nodes ns ON ns.NodeID=ns1.ParentID JOIN SystemConf sc ON sc.NodeID=ns.NodeID WHERE ns1.NodeID=$id AND (ns.Type='COMPort' OR ns.Type='IPPort')";
  $sth = Query $dbh $query or die "$Mysql::db_errstr";

  $new_type = "";
  $new_name = "";
  $new_value = "";

  my $new_port = $indoc->createElement("port");

  while ( $line = $sth->fetchrow_arrayref )
  {
    $new_type  = $$line[0];
    $new_name  = $$line[1];
    $new_value = $$line[2];

    my $new_parameter = $indoc->createElement("parameter");
    $new_port->appendChild($new_parameter);
    $new_parameter->setAttribute("name", $new_name);

    my $new_text = $indoc->createTextNode("text");
    $new_text->setData($new_value);
    $new_parameter->appendChild($new_text);
  }

  if ( $new_type ne "" )
  {
    $new_port->setAttribute("type", $new_type);
    $task->appendChild($new_port);
  }

  undef $sth;
}

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

my $req = HTTP::Request->new(POST => 'http://localhost/cgi-bin/connection.pl');
$req->content_type('application/x-www-form-urlencoded');
$req->content("xml=$final");
my $res = $ua->request($req);

if($res->is_success)  {
    print $res->content;
}
else
{
  print "<data/>";
}

$indoc->dispose;

undef $dbh;

