#! /usr/bin/perl -w
################################################################################
# Copyright 2005-2011 MERETHIS
# Centreon is developped by : Julien Mathis and Romain Le Merlus under
# GPL Licence 2.0.
# 
# This program is free software; you can redistribute it and/or modify it under 
# the terms of the GNU General Public License as published by the Free Software 
# Foundation ; either version 2 of the License.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along with 
# this program; if not, see <http://www.gnu.org/licenses>.
# 
# Linking this program statically or dynamically with other modules is making a 
# combined work based on this program. Thus, the terms and conditions of the GNU 
# General Public License cover the whole combination.
# 
# As a special exception, the copyright holders of this program give MERETHIS 
# permission to link this program with independent modules to produce an executable, 
# regardless of the license terms of these independent modules, and to copy and 
# distribute the resulting executable under terms of MERETHIS choice, provided that 
# MERETHIS also meet, for each linked independent module, the terms  and conditions 
# of the license of that module. An independent module is a module which is not 
# derived from this program. If you modify this program, you may extend this 
# exception to your version of the program, but you are not obliged to do so. If you
# do not wish to do so, delete this exception statement from your version.
# 
# For more information : contact@centreon.com
# 
# SVN : $URL: http://svn.centreon.com/branches/centreon-2.3.x/bin/centcore $
# SVN : $Id: centcore 12762 2011-12-09 15:20:18Z jmathis $
#
####################################################################################
#
# Script init
#

use strict;
use POSIX qw(mkfifo);
use DBI;
use File::Copy;
use File::Path qw(mkpath);

use vars qw($debug $LOG %status $generalcounter $stop $method $perfdataSync $logSync $timeBetween2SyncPerf);
use vars qw($mysql_user $mysql_passwd $mysql_host $mysql_database_oreon $mysql_database_ods);
use vars qw($con $ssh $scp $rsync $rsyncWT $echo $sudo $installedPath $timeout);
use vars qw(%commandBuffer);

if (POSIX::getuid() == 0 ) { 
    print STDERR "You must not execute centcore with root user \n"; exit 1;
}

#######################################
# Initiate options
$debug = 0;
$timeout = 5; 
$timeBetween2SyncPerf = 60;
$perfdataSync = 1;
$logSync = 1;

#######################################
# Configure Paths

my $installedPath = "/srv/centreon";
my $LOG = "/var/log/centreon/centcore.log";
my $PID = "/var/run/centreon/centcore.pid";
my $cmdFile = "/var/lib/centreon/centcore.cmd";
my $VARLIB = "/var/lib/centreon";

$echo = "/bin/echo";
$ssh = "/usr/bin/ssh";
$scp = "/usr/bin/scp";
$rsync = "rsync";
$rsyncWT = $rsync;
$sudo = "sudo";

#######################################
# Binaries Options
$ssh	.= " -o ConnectTimeout=$timeout ";
$rsync	.= " --timeout=$timeout ";
$scp	.= " -o ConnectTimeout=$timeout ";

#######################################
# Initiate Flag : 
# Never change this options. 
#
my $stop = 1;
my $cfg;

#######################################
# Include Configuration Data
require "/etc/centreon/conf.pm";

sub catch_zap {
    $stop = 0;
    writeLogFile("Receiving order to stop...");
}

###########################################################
# Function to write logfile
#
sub writeLogFile($){
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time());
    open (LOG, ">> ".$LOG) || print "can't write $LOG: $!";

    # Add initial 0 if value is under 10
    $hour = "0".$hour if ($hour < 10);
    $min = "0".$min if ($min < 10);
    $sec = "0".$sec if ($sec < 10);

    print LOG "$mday/".($mon+1)."/".($year+1900)." $hour:$min:$sec - ".$_[0]."\n";
    close LOG or warn $!;
}

# checking if pid file exists.
if (-x $PID){
    writeLogFile("centcore already running. can't launch again....");
    exit(2);
}

sub killChild(){
    ;
}

###########################################################
# Init signal actions
#
$SIG{'INT'}  	= \&catch_zap;
$SIG{'CHLD'} 	= \&killChild;

###########################################################
# Declare Functions
#
sub parseRequest($);
sub GetAllNagiosServerPerfData();
sub moveCmdFile($);
sub syncArchives($);

# Add the handles for our programs into the readset.
# In other words, we're keeping track of these handles.

my $timeSyncPerf = 0;
my $timeNagiosLogs = 0;
my $difTime = 10;


###########################################################
# Function to move command file on temporary file
#
sub moveCmdFile($){
    my $CMDFILE = $_[0];
    if (move($CMDFILE, $CMDFILE."_read")){
	return(1);
    } else {
	writeLogFile("Cannot move $CMDFILE to ".$CMDFILE."_read");
	return(0);
    }
}

###########################################################
# Function to remove temporary command file 
#
sub removeTmpCmdFile($){
    my $CMDFILE = $_[0];
    if (unlink($CMDFILE."_read")){
	return(1);
    } else {
	writeLogFile("Can't remove temporary command file.");
	return(0);
    }
}

sub GetAllNagiosServerPerfData(){
    CheckMySQLConnexion();
    my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `localhost` = '0' AND `ns_activate` = '1'");
    if (!$sth2->execute()) {
	writeLogFile("Error when getting server properties : ".$sth2->errstr);
    }
    while (my $data = $sth2->fetchrow_hashref()){
	if ($perfdataSync == 1) {
		GetPerfData($data->{'id'});
	}
	if ($logSync == 1) {
		GetLogFile($data->{'id'});
    }
    }
    $sth2->finish();
    $con->disconnect();
    return;
}

# -------------------
#      Functions 
# -------------------

sub getNagiosConfigurationField($$){
    CheckMySQLConnexion();
    my $sth2 = $con->prepare("SELECT ".$_[1]." FROM `cfg_nagios` WHERE `nagios_server_id` = '".$_[0]."'");
    if (!$sth2->execute()) {
	writeLogFile("Error when getting server properties : ".$sth2->errstr);
    }
    my $data = $sth2->fetchrow_hashref();
    $sth2->finish();
    return $data->{$_[1]};
}

sub getLocalOptionsField($){
    CheckMySQLConnexion();
    my $sth2 = $con->prepare("SELECT `value` FROM `options` WHERE `key` LIKE '".$_[0]."' LIMIT 1");
    if (!$sth2->execute()) {
	writeLogFile("Error when getting general options properties : ".$sth2->errstr);
    }
    my $data = $sth2->fetchrow_hashref();
    $sth2->finish();
    return $data->{'value'};
}

sub getLocalServerID(){
    CheckMySQLConnexion();
    my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1'");
    if (!$sth2->execute()) {
	writeLogFile("Error when getting server properties : ".$sth2->errstr);
    }
    my $id = $sth2->fetchrow_hashref();
    $sth2->finish();
    return $id->{'id'};
}

sub getServerConfig($){
    CheckMySQLConnexion();
    my $sth2 = $con->prepare("SELECT * FROM `nagios_server` WHERE `id` = '".$_[0]."' AND `ns_activate` = '1'");
    if (!$sth2->execute()) {
	writeLogFile("Error when getting server properties : ".$sth2->errstr."\n");
    }
    my $data = $sth2->fetchrow_hashref();
    $sth2->finish();
    return $data;
}

sub CheckMySQLConnexion() {
    while (!defined($con) || !$con->ping()) {
	if (!defined($con) || !$con->ping()) {
	    $con = DBI->connect("DBI:mysql:database=".$mysql_database_oreon.";host=".$mysql_host, $mysql_user, $mysql_passwd, {'RaiseError' => 0, 'PrintError' => 0, 'AutoCommit' => 1});
	    if (!defined($con)) {
		writeLogFile("Error when connecting to database : " . $DBI::errstr . "\n");
		sleep(2);
	    }
	} else {
	    sleep(2);	    
	    undef($con);
	    $con = DBI->connect("DBI:mysql:database=".$mysql_database_oreon.";host=".$mysql_host, $mysql_user, $mysql_passwd, {'RaiseError' => 0, 'PrintError' => 0, 'AutoCommit' => 1});
	}
    }
}

sub getPerfDataFile($$){
    my ($filename, $sth2, $data, $con, $poller_id);
    $con = $_[0];
    $poller_id = $_[1];
    
    # Create request
    my $request = "SELECT `nagios_perfdata` FROM `nagios_server` WHERE `id` = '".$poller_id."'";
    $sth2 = $con->prepare($request);
    if (!$sth2->execute()) {
	writeLogFile("Error when getting perfdata file : " . $sth2->errstr . "");
	undef($request);
	return "";
    }
    $data = $sth2->fetchrow_hashref();
    $filename = $data->{'nagios_perfdata'};

    # Free
    $sth2->finish();
    undef($data);
    undef($con);
    undef($request);
    return $filename;
}

#
# Send an external command on a remote server.
# Param : id_remote_server, external command
#

sub sendExternalCommand($$){
    # Init Parameters
    my $id = $_[0];
    my $cmd = $_[1];
    my $port = 22;
    my $stdout = '';

    # Get command file 
    my $command_file = getNagiosConfigurationField($id, "command_file");

    # Get server informations
    my $server_info = getServerConfig($id);

    if (defined($server_info->{'ssh_port'}) && $server_info->{'ssh_port'}) {
	$port = $server_info->{'ssh_port'};
    }

    # check if ip address is defined
    if (defined($server_info->{'ns_ip_address'})) {

	$cmd =~ s/\\/\\\\/g;

	if ($server_info->{'localhost'} == 1) {
		my $result = waitPipe($command_file);
		if ($result == 0) {
			writeLogFile("External command on Central Server: ($id) : \"".$cmd."\"");
			my $cmd = "echo \"".$cmd."\" >> ".$command_file."\n";
			$stdout = `$cmd`;		
		} else {
			writeLogFile("Cannot write external command on central server : \"".$cmd."\"");
		}
	} else {
		writeLogFile("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\"");
		my $cmd = "$ssh -q ".$server_info->{'ns_ip_address'}." -p $port 'echo \"".$cmd."\" >> ".$command_file."'\n";
		$stdout = `$cmd`;
	}

	if (defined($stdout) && $stdout){
	    writeLogFile("Result : $stdout\n");
	}

	# Free
	undef($stdout);
	undef($cmd);
    } else {
	writeLogFile("Ip address not defined for poller $id");
    }
    # Free
    undef($id);
    undef($cmd);
    undef($server_info);
    undef($command_file);
}

#######################################
# Wait Nagios Pipe availability
sub waitPipe($) {
	my $i = 0;
	while (! -p $_[0]) {
		sleep(1);
		$i++;
		if ($i >= 30) {
			return 1;
		}
	}
	return 0;
}



#
# Get PerfdataFile
#

sub getNagiosInformation($){

}

sub GetPerfData($){
    # init Values
    my $id = $_[0];
    my $port = 22;

    # Check MySQL Connection
    CheckMySQLConnexion();

    # Get Server Infos
    my $server_info = getServerConfig($id);
    my $distantconnexion = $server_info->{'ns_ip_address'};

    # Check port configuration
    if (defined($server_info->{'ssh_port'}) && $server_info->{'ssh_port'}) {
	$port = $server_info->{'ssh_port'};
    }

    # Where is perfdata file on remote poller 
    my $distantperffile = getPerfDataFile($con, $id);
    my $distantperffile_buffer = $distantperffile . ".buff";
		
	if (!defined($distantperffile_buffer) || !$distantperffile_buffer) {
		writeLogFile("perfdata file not configured for poller $id ($distantconnexion)");
		return;
	}

    # Build destination directory reserved for this poller
    my $localbasevardir = "$VARLIB/perfdata/$id";

    # check if directory exists
    if (!-d $localbasevardir) {
		mkpath $localbasevardir;
    }

    my $localtmpperffile = "$localbasevardir/service-perfdata";
    my $localperffile = getPerfDataFile($con, getLocalServerID());
    my $move_cmd = "rm -f $distantperffile_buffer 2> /dev/null; cp $distantperffile $distantperffile_buffer 2> /dev/null ; echo \"# New File\" > $distantperffile";
    
    # Get Perfdata file
    if (!defined($distantperffile)) {
	writeLogFile("Cannot get perfdata file. Unkown perfdata file on poller $id");
    } else {
	# Rename perfdata file
	my $cmd = "$ssh -q ".$server_info->{'ns_ip_address'}." -p $port '".$move_cmd."'";
	writeLogFile($cmd) if ($debug);
	`$cmd`;
	
	# Get Perfdata File
	writeLogFile("$scp -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile") if ($debug);
	`$scp -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile 2>> /dev/null`;
	
	# Write data from distant poller on local file for centstorage
	if (-f $localtmpperffile){
	    # Concat poller perfdata to central perfdata.
	    writeLogFile("cat $localtmpperffile >> $localperffile") if ($debug);
	    `cat $localtmpperffile >> $localperffile`;

	    # Remove old file
	    if (!unlink($localtmpperffile)) {
		writeLogFile("Cannot Remove performance data file : $localtmpperffile");
	    }
	}
    }
}

sub GetLogFile($){
    # Init values
    my $id = $_[0];
    my $port = 22;
    my $last_access;

    # Get Server informations
    my $server_info = getServerConfig($id);

    # Check port configuration
    if (defined($server_info->{'ssh_port'}) && $server_info->{'ssh_port'}) {
	$port = $server_info->{'ssh_port'};
    }

    # Check configuration
    my $distantconnexion = $server_info->{'ns_ip_address'};
    if (!defined($distantconnexion)) {
	writeLogFile("IP address not defined for poller $id");	
    }

    # Set local directory
    my $localDir = $VARLIB."/log/$id/";

    # Create tmp directory
    mkpath $localDir if (!-d $localDir);

    # Get logs if dir exists
    if (-d $localDir){

	# Get distant log file path
	my $distantlogfile = getNagiosConfigurationField($id, "log_file");;
	my $locallogfile = $localDir."nagios.log";

	# check if we can do the transfert
	if (defined($distantconnexion) && defined($distantlogfile)) {	    
	    # Check if nagios.log file is up to date
	    my $flag;
	    if (-f $localDir.".nagios.log.flag") {
		# Cet old flag
		my $cmd = $localDir.".nagios.log.flag";
		my $value = `cat $cmd`;
		$value =~ s/\n//g;
		undef($cmd);
		
		# Check update 
		my $check_cmd = "$ssh  -p $port -q $distantconnexion 'stat  -c \'%Y\' $distantlogfile'";
		writeLogFile("Get Log Files - stat: $check_cmd") if ($debug);
		$last_access = `$check_cmd`;
		writeLogFile("Get Log File - stat: Finished") if ($debug);
		$last_access =~ s/\n//g;

		# Check buffer
		if ($value !~ $last_access) {
		    $flag = 1;
		} else {
		    $flag = 0;
		}
		
	    } else {
		$flag = 1;
	    }
	    
	    if ($flag == 1) {
		# Get file with rsync
		my $cmd = "$scp -P $port $distantconnexion:$distantlogfile $locallogfile 2>> /dev/null";
		`$cmd`;
		writeLogFile($cmd) if ($debug);
		if ($? ne 0) {
		    writeLogFile("Cannot get log file or log file doesn't exists on poller $id");
		}
	    }

	    # Update or create time buffer
	    my $buffer_cmd = "echo '$last_access' > ".$localDir.".nagios.log.flag";
	    `$buffer_cmd`; 
	    undef($buffer_cmd);

	}
    } else {
	writeLogFile("Unable to create $localDir. Can get nagios log file for poller $id");
    }
}

##################################################
# Send config files to a remote server 
#
sub sendConfigFile($){
    # Init Values
    my $id = $_[0];
    my $port = 22;

    my $cfg_dir = getNagiosConfigurationField($id, "cfg_dir");
    my $server_info = getServerConfig($id);
    
    # Check Port configuration
    if (defined($server_info->{'ssh_port'}) && $server_info->{'ssh_port'}) {
	$port = $server_info->{'ssh_port'};
    }

    my $origin = $installedPath."/filesGeneration/nagiosCFG/".$id."/*";
    my $dest = $server_info->{'ns_ip_address'}.":$cfg_dir";
    
    # Send data with rsync
    my $cmd = "$scp -P $port $origin $dest";
    writeLogFile("Start: Send config files on poller $id");
    `$cmd`;
    undef($cmd);
    writeLogFile("End: Send config files on poller $id");
    
    # Send configuration for Centreon Broker
    if ( -e $installedPath."/filesGeneration/broker/".$id) {
	    $cfg_dir = $server_info->{'centreonbroker_cfg_path'};
	    $origin = $installedPath."/filesGeneration/broker/".$id."/*.xml";
	    $dest = $server_info->{'ns_ip_address'}.":$cfg_dir";
	    my $cmd = "$scp -P $port $origin $dest";
	    writeLogFile("Start: Send Centreon Broker config files on poller $id");
	    `$cmd`;
	    undef($cmd);
	    writeLogFile("End: Send Centreon Broker config files on poller $id");
    }
	
    # Free
    undef($cfg_dir);
    undef($server_info);
}

##################################################
# Function for initialize Nagios :
# Parameters :
#   - start
#   - restart
#   - stop
#
sub initNagios($$){
    my $id = $_[0];
    my $options = $_[1];
    my $port = 22;
    my ($cmd, $stdout);

    # Get configuration
    my $conf = getServerConfig($id);

    # Check port configuration
    if (defined($conf->{'ssh_port'}) && $conf->{'ssh_port'}) {
        $port = $conf->{'ssh_port'};
    }
    
    if (defined($conf->{'ns_ip_address'}) && $conf->{'ns_ip_address'}) {
	# Launch command
	$cmd = "$ssh -p $port ".$conf->{'ns_ip_address'}." $sudo ".$conf->{'init_script'}." ".$options;
	$stdout = `$cmd`;
    } else {
	writeLogFile("Cannot $options Nagios for poller $id");
    }
    
    # Logs Actions
    writeLogFile("Init Script : '$sudo ".$conf->{'init_script'}." ".$options."' On poller ".$conf->{'ns_ip_address'}." ($id)");
    my $line;
    foreach $line (split(/\n/, $stdout)){
	writeLogFile("NAGIOS : ".$line);
    }

    # Free
    undef($line);
    undef($conf);
    undef($cmd);
    undef($stdout);
}

##################################################
# Function for synchronize SNMP trap configuration
# 
sub syncTraps($) {
    my $id = $_[0];
    my $port = 22;

    # Check MySQL Connexion
    CheckMySQLConnexion();

    if ($id != 0) {
        # Get configuration
        my $ns_server = getServerConfig($id);

        # check port configuration
        if (defined($ns_server->{'ssh_port'}) && $ns_server->{'ssh_port'}) {
            $port = $ns_server->{'ssh_port'};
        }

        if ($id != 0) {
            `$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`;
            writeLogFile("$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/") if ($debug);

            my $ls = `ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l`;
            writeLogFile("ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l") if ($debug);

            if ($ls > 1) {
                `$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`;
                writeLogFile("$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf ".$ns_server->{'ns_ip_address'}.":/etc/snmp/centreon_traps/") if ($debug);                
            }
        }
    } else {
        # synchronize Archives for all pollers
        my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'");
        if (!$sth2->execute) {
            die "Error:" . $sth2->errstr . "\n";
        } else {
            while (my $server = $sth2->fetchrow_hashref()) {
                # Get configuration
                my $ns_server = getServerConfig($server->{'id'});

                # check port configuration
                if (defined($ns_server->{'ssh_port'}) && $ns_server->{'ssh_port'}) {
                    $port = $ns_server->{'ssh_port'};
                }

                if ($id == 0) {
                    `$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`;
                    writeLogFile("$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/") if ($debug);

                    my $ls = `ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l`;
                    writeLogFile("ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l") if ($debug);

                    if ($ls > 1) {
                        `$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`;
                        writeLogFile("$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf ".$ns_server->{'ns_ip_address'}.":/etc/snmp/centreon_traps/") if ($debug);                        
                    }
                }

            }
        }
    }
}

sub testConfig($) {
    my $id = $_[0];
    my $port = 22;

    my $cfg_dir = getNagiosConfigurationField($id, "cfg_dir");
    my $data = getServerConfig($id);
    
    if (defined($data->{'ssh_port'}) && $data->{'ssh_port'}) {
	$port = $data->{'ssh_port'};
    }
    
    my $distantconnexion = $data->{'ns_ip_address'};
    my $cmd = "$ssh -p ".$port." $distantconnexion $sudo ".$data->{'nagios_bin'}." -v $cfg_dir/nagios.cfg";
    my $stdout = `$cmd`;
    undef($cmd);
    undef($data);
    undef($distantconnexion);
    writeLogFile("$stdout\n");
    undef($cfg_dir);
}

sub syncArchives($) {
    my $id = $_[0];
    my $port = 22;
    
    # Check MySQL Connexion
    CheckMySQLConnexion();
    
    # Get configuration
    my $ns_server = getServerConfig($id);
    
    if (defined($ns_server->{'ssh_port'}) && $ns_server->{'ssh_port'}) {
	$port = $ns_server->{'ssh_port'};
    }
    
    if ($id != 0) {
	# Sync Archive for one poller
	if (! -d "$VARLIB/log/".$ns_server->{'id'}."/archives/") {
	    if (! -d "$VARLIB/log/".$ns_server->{'id'}."/archives/") {
		mkpath "$VARLIB/log/".$ns_server->{'id'}."/archives/";
	    }
	}
	my $sth = $con->prepare("SELECT `log_archive_path` FROM `cfg_nagios` WHERE `nagios_server_id` = '".$id."' AND `nagios_activate` = '1'");
	if ($sth->execute()) {
	    my $data = $sth->fetchrow_hashref();
	    
	    # Archive Sync
	    writeLogFile("$rsync --port=$port -c ".$ns_server->{'ns_ip_address'}.":".$data->{'log_archive_path'}."/*.log $VARLIB/log/".$ns_server->{'id'}."/archives/") if ($debug);
	    
	    `$rsyncWT --port=$port -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/*.log $VARLIB/log/$ns_server->{'id'}/archives/ 2>> /dev/null`;
	    undef($data);
	} else {
	    print "Can't get archive path for poller ".$ns_server->{'id'}." (".$ns_server->{'ns_address_ip'}.") -> ".$sth->errstr;
	}
    } else {
	# synchronize Archives for all pollers
	my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'");
	if (!$sth2->execute) {
	    die "Error:" . $sth2->errstr . "\n";
	} else { 
	    while (my $server = $sth2->fetchrow_hashref()) {
		writeLogFile("Receive Order to synchronize all archives of all pollers");
		syncArchives($server->{'id'});
		undef($server);
	    }
	    undef($sth2);
	}
    }
}

sub parseRequest($){
    if (!$_[0]) {
		return ;
    }

    # Checks keys for launching commands

    if ($_[0] =~ /^RESTART\:([0-9]*)/){
		initNagios($1, "restart");
    } elsif ($_[0] =~ /^RELOAD\:([0-9]*)/){
		initNagios($1, "reload");
    } elsif ($_[0] =~ /^START\:([0-9]*)/){
		initNagios($1, "start");
    } elsif ($_[0] =~ /^STOP\:([0-9]*)/){
		initNagios($1, "stop");
    } elsif ($_[0] =~ /^SENDCFGFILE\:([0-9]*)/){
		sendConfigFile($1);
    } elsif ($_[0] =~ /^TEST\:([0-9]*)/){
		# Experimental
		testConfig($1);
    } elsif ($_[0] =~ /^SYNCTRAP\:([0-9]*)/){
		syncTraps($1);
    } elsif ($_[0] =~ /^SYNCPLUGINS\:([0-9]*)/){
		;
    } elsif ($_[0] =~ /^SYNCARCHIVES\:([0-9]*)/){
		syncArchives($1);
    } elsif ($_[0] =~ /^EXTERNALCMD\:([0-9]*)\:(.*)/){
		storeCommands($1, $2);
    }
}

# Store commands in order to group commands to send.
sub storeCommands($$) {
	my ($poller_id, $command) = @_;
	
	if (!defined($commandBuffer{$poller_id})) {
		$commandBuffer{$poller_id} = "";
	}
	$commandBuffer{$poller_id} .= $command . "\n";
}

# Write in log file that program is starting
sub signalstartprogram() {
	# Starting centcore Engine
	writeLogFile("Starting centcore engine...");
	writeLogFile("PID : ".$$."");
}

# Write in log file that program is stoping
sub signalstopprogram() {
    writeLogFile("Stopping centcore engine...");
    if (!unlink($PID)) {
		writeLogFile("Error When removing pid file : $!") ;
    }
}

# Writing PID
sub writepid($) {
	if (!defined($_[0]) || $_[0] == 0) {
		writeLogFile("Cannot write pid file");
	}
	open (PID, ">> ".$PID) || print "can't write PID : $!";
	print PID $_[0] ;
	close PID or warn $!;
}


# Begin centcore 
my $pid  = 0;

if ($pid ne fork()) {

    # Fork 
    if (!fork()) {
	
		signalstartprogram();
		writepid($$);
	
		while ($stop) {  
	
		    if (-e $cmdFile) {
			if (moveCmdFile($cmdFile) && open(FILE, "< $cmdFile"."_read")) {
			    while (<FILE>){
				parseRequest($_);
			    }
			    my $poller;
			    foreach $poller (keys(%commandBuffer)) {
				if (length($commandBuffer{$poller}) != 0) {
				    sendExternalCommand($poller, $commandBuffer{$poller});
				    $commandBuffer{$poller} = "";
				}
			    }
			    writeLogFile("Error When removing ".$cmdFile."_read file : $!") if (!unlink($cmdFile."_read"));
			}
			close(FILE);
		    }
		    if (defined($timeSyncPerf) && $timeSyncPerf) {
			$difTime = time() - $timeSyncPerf;
		    }
		    if ((defined($difTime) && $timeBetween2SyncPerf <= $difTime) || $timeSyncPerf == 0){
				# Get PerfData on Nagios Poller
				GetAllNagiosServerPerfData();		
				$timeSyncPerf = time();
		    }
		    sleep(1);
		}
	    
	    signalstopprogram();
	}
    exit 0;
}

waitpid($pid, 0);
exit(1);


unlink($PID);
writeLogFile("Centcore stop...");
exit();

__END__
