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



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

my $query;
$query = "SELECT ns.NodeID, ns.ParentId, ns.Type, ns.Name FROM Nodes ns, SystemConf sc WHERE ns.NodeID=sc.NodeID AND sc.Name='Active' AND sc.Value!=1 ORDER BY NodeID";
my $sth = Query $dbh $query or die "$Mysql::db_errstr";

my $line;
while ( $line = $sth->fetchrow_arrayref )
{
  my $nodeid   = $$line[0] if $$line[0] ne "";
  my $parentid = $$line[1] if $$line[1] ne "";
  my $type     = $$line[2] if $$line[2] ne "";
  my $name     = $$line[3] if $$line[3] ne "";

  my $nametag = $outdoc->createElement("name");
  $data->appendChild($nametag);
  $nametag->setAttribute("id", $nodeid);
  $nametag->setAttribute("parentid", $parentid);
  $nametag->setAttribute("type", $type);
  if ( $name ne "" )
  {
    my $cdata=$outdoc->createCDATASection("cdata");
    $cdata->setData("$name");
    $nametag->appendChild($cdata);
  }
}

undef $sth;

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

print $final;

$outdoc->dispose;

undef $dbh;
