#!/usr/bin/perl -w

use strict;

my $home="/usr/local/controller/scripts";

use XML::DOM;
use DBI;
require "$home/connect.pl";
require "$home/log.pl";

#set this to 1 if you want logs
my $dolog = 0;

my $reqs;

#checking req.pl copy running.

open(LIMIT, "ps ax | grep -v grep | grep -c req.pl |");

while(<LIMIT>)
{
  chomp;
  $reqs = $_;
}
close(LIMIT);

if($reqs > 1) { 
    print "A copy of req.pl is already running. Exiting...\n";    
    exit(); 
}

my $appserv = configuration("appserv");

my $strtopars="";
my $sql="";

# Create a user agent object
use LWP::UserAgent;
my $localaddress = configuration('localaddress');
#print "Local Address: ".$localaddress."\n";
@LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => $localaddress) if $localaddress ne "";
my $ua = LWP::UserAgent->new;
$ua->agent("ControllerGetConf ");

while ($strtopars eq "") {
# Create a request
     my $req = HTTP::Request->new(GET => "http://$appserv/ControllerConfServlet/controllerconfservlet");
#     $req->content_type('application/x-www-form-urlencoded');
#     $req->content('match=www&errors=0');

# Pass request to the user agent and get a response back
     my $res = $ua->request($req);

# Check the outcome of the response
     if ($res->is_success) {
         $strtopars= $res->content;
     } else {
         print "Can't connect. Check servlet working.\n";
	     sleep(10);
     }
}
#   print "Content: \n $strtopars";

#open(XMLFILE, "> xml_from_server.xml");
#print XMLFILE $strtopars;
#close(XMLFILE);

    my $parser = new XML::DOM::Parser;
    my $doc = $parser->parse($strtopars);

    my $tables = $doc->getElementsByTagName("table");
    my $tables_number = $tables->getLength;

for ( my $i = 0; $i < $tables_number; $i++ ) {
  my $table = $tables->item ($i);
  my $table_name = $table->getAttribute("name");
  $sql .= "DROP TABLE IF EXISTS $table_name;\n";

  $sql .= "CREATE TABLE $table_name (";
  my $header = $table->getElementsByTagName("header");
  my $columns = $header->item(0)->getElementsByTagName("column");
  my $columns_number = $columns->getLength;
  for ( my $j = 0; $j < $columns_number; $j++ ) {
    my $column = $columns->item($j);
    my $column_name = $column->getAttribute("name");
    my $column_type = $column->getAttribute("type");
    $sql .= "$column_name " . uc($column_type);
    $sql .= ", " if $j != $columns_number - 1;
  }

  my $keys = $header->item(0)->getElementsByTagName("key");
  my $keys_number = $keys->getLength;
  if( $keys_number != 0 )
  {
	  $sql .= ", PRIMARY KEY(";
	  for ( my $j = 0; $j < $keys_number; $j++ ) {
	    my $key = $keys->item($j);
	    my $key_name = $key->getAttribute("name");
	    $sql .= "$key_name";
	    $sql .= ", " if $j != $keys_number - 1;
	  }
	  $sql .= ")";
  }
	
  $sql .= ");\n";
  
  my $records = $table->getElementsByTagName("records");
  my $rows = $records->item(0)->getElementsByTagName("row");
  my $rows_number = $rows->getLength;
  for ( my $j = 0; $j < $rows_number; $j++ ) {
    my $row = $rows->item($j);
    my $columns = $row->getElementsByTagName("column");
    my $columns_number = $columns->getLength;
    my $names = "";
    my $values = "";
    for ( my $k = 0; $k < $columns_number; $k++ ) {
      my $column = $columns->item($k);
      my $column_name = $column->getAttribute("name");
      my $column_value = "";
      if(defined($column->getChildNodes->item(0))) {
        $column_value = $column->getChildNodes->item(0)->getNodeValue;
	$column_value =~ s/'/\\'/sg;
    $column_value = substr($column_value,0,255);
      }
      $names .= $column_name;
      $names .= ", " if $k != $columns_number - 1;
      $values .= "'$column_value'";
      $values .= ", " if $k != $columns_number - 1;
      
    }
$sql .= "INSERT INTO $table_name ($names) VALUES ($values);\n";

  }
}

$doc->dispose;

$sql .= "CREATE TABLE IF NOT EXISTS PollData".
    "(time BIGINT NOT NULL, value VARCHAR(255),id INT NOT NULL,".
    "sync SMALLINT default 0,status SMALLINT default 0,".
    "PRIMARY KEY (id,time));\n";

$sql .= "CREATE TABLE IF NOT EXISTS JSONPollData".
    "(sync INT NOT NULL DEFAULT 0, JSONvalue TEXT);\n";

$sql .= "CREATE TABLE IF NOT EXISTS Alarms".
    "(time BIGINT NOT NULL, id INT NOT NULL, status SMALLINT default 0,".
    "raised TINYINT default 1, message VARCHAR(255), sender VARCHAR(255), sync SMALLINT default 0,".
    "isAlarm SMALLINT NOT NULL default 0, PRIMARY KEY (id, status, time));\n";

$sql .= "CREATE TABLE IF NOT EXISTS CurrentStatus".
    "(id INT NOT NULL, status INT default 0,".
    "raised INT default 1, value VARCHAR(255), ".
    "time BIGINT(20) NOT NULL default 0, ".
    "PRIMARY KEY (id, status), INDEX(id));\n";

$sql .= "CREATE TABLE IF NOT EXISTS storedData".
    "(id int(11) NOT NULL auto_increment,".
    " name VARCHAR(255) NOT NULL default '', time bigint(20) NOT NULL,".
    " description text default NULL, type VARCHAR(255) default NULL,".
    " typedesc VARCHAR(255) default NULL, data mediumblob, PRIMARY KEY(id)".
    ") TYPE=MyISAM;\n";

my $dbh = satisMysqlConnect();

if($dolog) {
	dolog("request.log",$sql,">");
}

my $query;
foreach $query(split(/;\n/, $sql)) {
    $dbh->do($query);
}


##undef $sth;
undef $dbh;
print "Update finished. Restarting polling...\n";
#Starting polling process
system("(/usr/local/controller/rc.d/spectrum.sh stop)");
system("(/usr/local/controller/rc.d/010.connector.sh start)");
sleep 1;
system("(/usr/local/controller/rc.d/020.pmanager.sh start)");
system("(/usr/local/controller/rc.d/spectrum.sh start)");

#Getting local mnemo
system("(/usr/local/controller/scripts/mnemo.pl &)");
