#! /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$
# SVN : $Id$
#
####################################################################################

# Message type
# 0 -> Service Alerts
# 1 -> Host Alerts
# 2 -> Service notification
# 3 -> Host Notification
# 4 -> All nagios Warning
# 5 -> All logs
# 6 -> Service Current State
# 7 -> Host Current State
# 8 -> Service Initial State
# 9 -> Host Initial State
# 10 -> Service Acknowledgement
# 11 -> Host Acknowledgement

use strict;
use warnings;
use DBI;
use File::stat;
use Getopt::Long;
use POSIX;
use vars qw($mysql_user $mysql_passwd $mysql_host $mysql_database_oreon 
            $mysql_database_ods $opt_h $opt_a $opt_p $opt_s $data $LOG);

require "/DBA/centreon/2.4.5/etc/conf.pm";

# Globals
my $VarLib = "/DBA/centreon/2.4.5/var/lib";
$LOG = "/DBA/centreon/2.4.5/log/logAnalyser.log";
my ($dbh, $dbhoreon) = (undef, undef);
my $appID = undef;
my $msg_type5_disabled = 0;
my $cpt = -1;
my $ctime = 0;
my $last_line_read;
my $flag_position_file;
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
my $timeLaunch = time();
my $retention = undef;
my $cur_instance = undef;

# Write logs in a file.
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 $!;
}

=head2 set_lock($dbcon)

Activate the lock in database.

Return the unique identifier of this application and the previous
launch time.

=cut
sub set_lock($) {
    my ($dbconn) = @_;
    my $sth = $dbconn->prepare("SELECT id, running, time_launch FROM cron_operation WHERE name LIKE 'logAnalyser'");
    if (!$sth->execute) {
        die "Error:" . $sth->errstr . "\n";
    }
    my $data = $sth->fetchrow_hashref();
    my ($appID, $sthbis, $last_launch_time) = undef;

    if (defined($data->{'id'})) {
        if (!defined($data->{"running"}) || $data->{"running"} == 0) {
            $appID = $data->{"id"};
            $last_launch_time = $data->{time_launch};
            $sthbis = $dbhoreon->prepare("UPDATE cron_operation SET running = '1', time_launch = '".time()."' WHERE id = '$appID'");
            if (!$sthbis->execute) {
                die "Error:" . $sthbis->errstr . "\n";
            }
            return ($appID, int($last_launch_time));
        }
        writeLogFile("logAnalyser already running...");
        exit 1;
    }
    $sthbis = $dbhoreon->prepare("INSERT INTO cron_operation (name, system, activate) VALUES ('logAnalyser', '1', '1')");
    if (!$sthbis->execute) {
        die "Error:" . $sthbis->errstr . "\n";
    }
    return ($appID, $timeLaunch);
}

=head2 unset_lock($dbconn, $appID)

Deactivate the lock in database.

=cut
sub unset_lock {
    my ($dbconn, $appID) = @_;
    my $sth = $dbconn->prepare("UPDATE cron_operation SET running = '0', last_execution_time = '" . (time() - $timeLaunch) . "' WHERE id = '$appID'");

    if (!$sth->execute()) {
        die "Error:" . $sth->errstr . "\n";
    }
}

=head2 clean_exit()

Enforce a proper exit in every case.

=cut
sub clean_exit {
    my $message = shift;

    if ($message) {
        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time());
        my $logmsg = "$mday/" . ($mon + 1) . "/" . ($year + 1900) . " $hour:$min:$sec -  $message";

        print $logmsg;
        writeLogFile($logmsg);
    }

    if ($cpt != -1) {
        my $rq = "UPDATE `instance` SET `log_flag` = '$cpt' WHERE `instance_id` = '$cur_instance'";
        my $res = $dbh->do($rq);
        if (!defined($res)) {
            write_flag_position_file();
            writeLogFile("SQL UPDATE Error:" . $dbh->errstr);
        }
    }
    
    if (defined $dbhoreon) {
        unset_lock($dbhoreon, $appID);
        $dbhoreon->disconnect();
    }
    if (defined $dbh) {
        $dbh->disconnect();
    }
    exit 0;
}

=head2 clear_flag_position_file($instance)



=cut
sub clear_flag_position_file($) {
    my ($instance) = @_;

    if (-f "$VarLib/log/$instance/.flag_position") {
        unlink("$VarLib/log/$instance/.flag_position")
            or writeLogFile("Cannot delete file '$VarLib/log/$instance/.flag_position' $!");
    }
}

sub write_flag_position_file {
    if (!open(FILE, "> ".$flag_position_file)){
        writeLogFile("Cannot open file : $flag_position_file (WRITE) $!");
        return;
    }
    print FILE $cpt;
    close(FILE);
}

=head2 parseFile($logFile, $instance)

Parse a nagios log file.

=cut
sub parseFile($$) {
    my ($logFile, $instance) = @_;
    my $lastCTime = 0;
    my $CTime = 0;
    my $historyFile = "$VarLib/log/$instance/.history";
    
    $flag_position_file = "$VarLib/log/$instance/.flag_position";
    if (!-f "$VarLib/log/") {
        mkdir("$VarLib/log/");
    }
    
    if (!-f "$VarLib/log/$instance") {
        mkdir("$VarLib/log/$instance");
    }
    # Get History Flag
    if (!open(FILE, $historyFile)){
        writeLogFile("Cannot open file : $historyFile (READ)");
    } else {
        while (<FILE>) {
            $lastCTime = $_;
            $lastCTime =~ s/\n//g;  
        }
        close(FILE);
    }
    
    # Get History Flag
    if (!open(FILE, $logFile)){
        writeLogFile("Cannot open file : $logFile (READ)");
        return;
    } else {
        my @tab;
        while (<FILE>) {
            if ($_ =~ m/\[([0-9]*)\]\ /) {
                $CTime = $1;
                $CTime =~ s/\n//g;  
                last;
            } else {
                writeLogFile("Cannot find ctime in first line for poller $instance");
                last;
            }
        }
        close(FILE);
    }
    
    # Decide if we have to read the nagios.log from the begining
    if ($CTime ne $lastCTime && $CTime ne 0 && $lastCTime ne 0){
        $last_line_read = 0;
    } else {
        my $sth_flag = $dbh->prepare("SELECT `log_flag` FROM `instance` WHERE `instance_id` = '".$instance."'");
        if (!$sth_flag->execute) {
            die "Error:" . $sth_flag->errstr . "\n";
        }
        $data = $sth_flag->fetchrow_hashref();
        $last_line_read = $data->{'log_flag'};
        
        if (!defined($last_line_read)) {
            writeLogFile("Alert : Cannot get last line read in DB for poller $instance");
            return ;
        }
        $sth_flag->finish();

        # Verify if we have more recent
        if (-f $flag_position_file) {
            if (!open(FILE, $flag_position_file)){
                writeLogFile("Cannot open file : $flag_position_file (READ) $!");
            } else {
                while (<FILE>) {
                    $last_line_read = $_;
                    $last_line_read =~ s/\n//g;
                }
                close(FILE);
            }
        }
    }
        
    # Open Log File for parsing
    if (!open (FILE, $_[0])){
        writeLogFile("Cannot open file : $_[0]");
        return;
    }
    
    # Init Counter
    $cpt = 0;
    
    # Skip old lines (already read)
    if (!$opt_a && $last_line_read) {
        while ($cpt < $last_line_read && <FILE>) {
            $cpt++;
        }
    }
    #
    # Now Read unknown log lines
    #
    while (<FILE>) {
        if ($_ =~ m/^\[([0-9]*)\]\sSERVICE ALERT\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            $tab[1] =~ s/\\/\\\\/g;
            $tab[1] =~ s/\'/\\\'/g;
            if (defined($tab[5])) {
                $tab[5] =~ s/\\/\\\\/g; 
                $tab[5] =~ s/\'/\\\'/g;
            } else {
                $tab[5] = "";
            }
            my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `type`, `retry`, `output`, `instance`) VALUES ('0', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."','".$tab[4]."','".$tab[5]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST ALERT\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            if (defined($tab[4]) && $tab[4]) {
                $tab[4] =~ s/\\/\\\\/g; 
                $tab[4] =~ s/\'/\\\'/g;
            } else {
                $tab[4] = "";
            }
            my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `status`,  `type`, `retry`, `output`, `instance`) VALUES ('1', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."','".$tab[3]."','".$tab[4]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sSERVICE NOTIFICATION\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[2] =~ s/\\/\\\\/g;
            $tab[2] =~ s/\'/\\\'/g;
            $tab[1] =~ s/\\/\\\\/g;
            $tab[1] =~ s/\'/\\\'/g;
            if (defined($tab[5])) {
                $tab[5] =~ s/\\/\\\\/g; 
                $tab[5] =~ s/\'/\\\'/g;
            } else {
                $tab[5] = "";
            }
            my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `notification_cmd`, `notification_contact`, `output`, `instance`) VALUES ('2', '$ctime', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$tab[4]."','".$tab[0]."','".$tab[5]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST NOTIFICATION\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            if (defined($tab[4])) {
                $tab[4] =~ s/\\/\\\\/g; 
                $tab[4] =~ s/\'/\\\'/g;
            } else {
                $tab[4] = "";
            }
            my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `notification_contact`, `host_name` , `status`, `notification_cmd`,  `output`, `instance`) VALUES ('3', '$ctime', '".$tab[0]."','".$tab[1]."', '".$tab[2]."', '".$tab[3]."','".$tab[4]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance`) VALUES ('7', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sSERVICE\sSTATE\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            $tab[1] =~ s/\\/\\\\/g;
            $tab[1] =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance`) VALUES ('6', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance`) VALUES ('9', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sSERVICE\sSTATE\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            $tab[1] =~ s/\\/\\\\/g;
            $tab[1] =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance`) VALUES ('8', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_SVC\_PROBLEM\;(.*)$/) {
            $ctime = $1;
            my @tab = split(/;/, $2);
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            $tab[1] =~ s/\\/\\\\/g;
            $tab[1] =~ s/\'/\\\'/g;
            if (!defined($tab[6])){
                $tab[6] = "";
            }
            $tab[6] =~ s/\\/\\\\/g;
            $tab[6] =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description`, `notification_contact`, `output`, `instance`) VALUES ('10', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[5]."', '".$tab[6]."','".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_HOST\_PROBLEM\;(.*)$/) {
            $ctime = $1;
            my @tab = split(/;/, $2);
            $tab[0] =~ s/\\/\\\\/g;
            $tab[0] =~ s/\'/\\\'/g;
            $tab[5] =~ s/\\/\\\\/g;
            $tab[5] =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `notification_contact`, `output`, `instance`) VALUES ('11', '$ctime', '".$tab[0]."', '".$tab[4]."', '".$tab[5]."','".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/){
            my $tab = $2;
            $ctime = $1;
            $tab =~ s/\\/\\\\/g; 
            $tab =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `output`, `instance`) VALUES ('4','$ctime', '".$tab."', '".$instance."')";
            my $res = $dbh->do($rq);
        } elsif ($_ =~ m/^\[([0-9]*)\]\s(.*)$/ && (!defined($msg_type5_disabled) || $msg_type5_disabled == 0)) {
            $ctime = $1;
            my $tab = $2;
            $tab =~ s/\\/\\\\/g; 
            $tab =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `output`, `instance`) VALUES ('5','$ctime', '".$tab."', '".$instance."')";
            my $res = $dbh->do($rq);
        }
        $cpt++;
    }
    close(FILE);
    
    # Add History
    if (!open(FILE, "> ".$historyFile)){
        writeLogFile("Cannot open file : $historyFile (WRITE)");
        return;
    } else {
        print FILE $CTime."\n";
        close(FILE);
    }
}

=head2 date_to_time($date)

Convert $date to a timestamp.

=cut
sub date_to_time($) {
    my $date = shift;

    $date =~ s|-|/|g;
    return int(`date -d $date +%s`);
}

=head2 time_to_date($timestamp)

Convert $timestamp to a human readable date.

=cut
sub time_to_date($) {
    my $timestamp = shift;
    chomp(my $result = `date -d \@$timestamp +%m-%d-%Y`);

    return $result;
}

=head2 parseArchive($instance, $localhost, $startdate)



=cut
sub parseArchive($$$) {
    my ($instance, $localhost, $startdate) = @_;
    my $archives;

    if ($localhost){
        my $sth = $dbhoreon->prepare("SELECT `log_archive_path` FROM `cfg_nagios`, `nagios_server` 
                                      WHERE `nagios_server_id` = '$instance' AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` AND `nagios_server`.`ns_activate` = '1' AND `cfg_nagios`.`nagios_activate` = '1'");
        if (!$sth->execute()) {
            die "Error:" . $sth->errstr . "\n";
        }
        $data = $sth->fetchrow_hashref();
        $archives = $data->{'log_archive_path'};
        $sth->finish();
    } else {
        $archives = "$VarLib/log/$instance/archives/";
    }

    $archives .= "/" if (!($archives =~ /\/$/));

    my @log_files = split /\s/,`ls $archives`;
    my $last_log = undef;

    if (!defined $startdate) {
        $last_log = time() - ($retention * 24 * 60 * 60);
    } else {
        $last_log = date_to_time($startdate);
    }
    foreach (@log_files) {
        $_ =~ /nagios\-([0-9\-]+).log/;
        my @time = split /\-/, $1;
        my $temp = $time[0]."/".$time[1]."/".$time[2];
        $temp = `date -d $temp +%s`;
        if ($temp > $last_log) {
            print "Parsing log file: $_\n";
            if (!(-r $archives.$_)) {
                writeLogFile("Error : cannot read file $archives$_");
            } else {
                writeLogFile($archives.$_."\n");
                parseFile($archives.$_, $instance);
            }
        }
    }
}

sub parseLogFile($$$) {
    # Get parameters
    my ($instance, $localhost, $previous_launch_time) = @_;
    my ($LOG_FILE, $archivepath);

    if ($localhost){
        my $sth = $dbhoreon->prepare("SELECT `log_file`, `log_archive_path` FROM `cfg_nagios`, `nagios_server` WHERE `nagios_server_id` = '$instance' AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` AND `nagios_server`.`ns_activate` = '1' AND `cfg_nagios`.`nagios_activate` = '1'");
        if (!$sth->execute()) {
            die "Error:" . $sth->errstr . "\n";
        }
        $data = $sth->fetchrow_hashref();
        $LOG_FILE = $data->{'log_file'};
        $archivepath = $data->{log_archive_path};
        $archivepath .= "/" if (!($archivepath =~ /\/$/));
        if (!(-r $LOG_FILE)) {
            writeLogFile("Error: cannot open $LOG_FILE");
            die "Error: failed to open $LOG_FILE.\n";
        }
        $sth->finish();
        my @now = localtime();
        my $archname = "$archivepath/nagios-" . time_to_date($timeLaunch) . "-$now[2].log";
        if (-f $archname) {
            my $st = stat($archname);
            if ($st->mtime > $previous_launch_time) {
                writeLogFile("Info: Parsing rotated file for instance $instance\n");
                parseFile($archname, $instance);
            }
        }
    } else {
        $LOG_FILE = "$VarLib/log/$instance/nagios.log";
        my $ROTATE_FILE = $LOG_FILE.".rotate";
        if (-e $ROTATE_FILE) {
            writeLogFile("Info: Parsing rotated file for instance $instance\n");
            parseFile($ROTATE_FILE, $instance);
            unlink($ROTATE_FILE);
        }
    }

    # Parse -> 

    parseFile($LOG_FILE, $instance);

    ##############################
    # Update statistics and flags
    my $rq = "UPDATE `instance` SET `log_flag` = '$cpt' WHERE `instance_id` = '$instance'";
    my $res = $dbh->do($rq);
    if (!defined($res)) {
        die "SQL UPDATE Error:" . $rq . "\n";
    }
    ##############################
    $cpt = -1;
    clear_flag_position_file($instance);
}

=head1 MAIN

Program starts here.

=cut

Getopt::Long::Configure('bundling');
GetOptions("h" => \$opt_h, "help" => \$opt_h,
           "a" => \$opt_a, "archives" => \$opt_a,
           "p=s" => \$opt_p, "poller" => \$opt_p,
           "s=s" => \$opt_s, "startdate" => \$opt_s);

if ($opt_h) {
    print " Usage : $0 :\n";
    print "    -a (--archives) load data from log archives to database\n";
    print "    -p (--poller <value>) load data from log archives to database from specific poller ID\n";
    print "    -s (--startdate <mm-dd-yyyy>) when parsing archives, start from a specific day\n";
    print "    -h (--help) show help\n";
    exit 0;
}

if (defined $opt_s) {
    if ($opt_s !~ m/\d{2}-\d{2}-\d{4}/) {
        print "Invalid start date provided\n";
        exit 1;
    }
}

$SIG{__DIE__} = \&clean_exit;

my $previous_launch_time;

# Init MySQL connections
$dbh = DBI->connect("DBI:mysql:database=$mysql_database_ods;host=$mysql_host", 
                    $mysql_user, $mysql_passwd, {'RaiseError' => 1});
$dbhoreon = DBI->connect("DBI:mysql:database=$mysql_database_oreon;host=$mysql_host", 
                         $mysql_user, $mysql_passwd, {'RaiseError' => 1});
($appID, $previous_launch_time) = set_lock($dbhoreon);

# Check if is db layer is centreon broker
my $dbLayer = $dbhoreon->prepare("SELECT `value` FROM `options` WHERE `key` = 'broker'");
if (!$dbLayer->execute()) {
    die "Error:" . $dbLayer->errstr . "\n";
}
my $dataLayer = $dbLayer->fetchrow_hashref();
if ($dataLayer->{'value'} eq "broker") {
    $dbLayer->finish();
    clean_exit();
}
$dbLayer->finish();

# Get conf Data
my $sth_config = $dbh->prepare("SELECT `archive_log`, `archive_retention`, `nagios_log_file`  FROM `config`");
if (!$sth_config->execute) {
    die "Error:" . $sth_config->errstr . "\n";
}
$data = $sth_config->fetchrow_hashref();
$sth_config->finish();
clean_exit("No configuration found in DB.\n") if (!$data->{'archive_log'});

$retention = $data->{'archive_retention'};

my $res;

if (defined($opt_p)) {
    $cur_instance = $opt_p;
    $res = $dbh->do("UPDATE `instance` SET `log_flag` = '0' WHERE `instance_id` = '$cur_instance'");
    if (!defined($res)) { 
        die "SQL UPDATE Error : UPDATE `instance` SET `log_flag` = '0'\n";
    };
    clear_flag_position_file($cur_instance);

    $res = $dbh->do("DELETE FROM `log` WHERE instance = '$cur_instance'");
    writeLogFile("SQL INSERT ERROR :TRUNCATE TABLE `log`") if (!defined($res));
    parseArchive($cur_instance, '0', $opt_s);
} else {
    my $flag = 0;
    my $sth2 = $dbhoreon->prepare("SELECT `id`, `name`, `localhost` FROM `nagios_server` WHERE `ns_activate` = 1");

    if (!$sth2->execute) {
        die "Error:" . $sth2->errstr . "\n";
    }
    while (my $ns_server = $sth2->fetchrow_hashref()) {
        my $sth1 = $dbh->prepare("SELECT `instance_name` FROM `instance` WHERE `instance_id` = '".$ns_server->{'id'}."' LIMIT 1");
        if (!$sth1->execute) {
            die "Error:" . $sth1->errstr . "\n";
        }
        if (!$sth1->rows()) {
            my $sthinsert = $dbh->prepare("INSERT INTO `instance` (`instance_id` , `instance_name` , `log_flag`) VALUES ('".$ns_server->{'id'}."', '".$ns_server->{'name'}."', '0');");
            if (!$sthinsert->execute) {
                die "Error:" . $sthinsert->errstr . "\n";
            }
            $sthinsert->finish();
        } else {
            my $sthupdate = $dbh->prepare("UPDATE `instance` SET `instance_name` = '".$ns_server->{'name'}."' WHERE `instance_id` = '".$ns_server->{'id'}."' LIMIT 1");
            if (!$sthupdate->execute) {
                die "Error:" . $sthupdate->errstr . "\n";
            }
            $sthupdate->finish();
        }
        $sth1->finish();
        $cur_instance = $ns_server->{id};
        if ($opt_a) {
            # Empty line counter
            $res = $dbh->do("UPDATE `instance` SET `log_flag` = '0' WHERE `instance_id` = $ns_server->{id}");
            if (!defined($res)) {
                die "SQL UPDATE Error : UPDATE `instance` SET `log_flag` = '0'\n";
            }
            if (!$flag) {
                if (!defined $opt_s) {
                    $res = $dbh->do("TRUNCATE TABLE `log`");
                    writeLogFile("SQL INSERT ERROR :TRUNCATE TABLE `log`") if (!defined($res));
                } else {
                    my $limit = date_to_time($opt_s);
                    $res = $dbh->do("DELETE FROM `log` WHERE `ctime` >= $limit");
                    writeLogFile("SQL ERROR: DELETE FROM `log`") if !defined($res);
                }
                $flag = 1;
            }
            clear_flag_position_file($ns_server->{'id'});
            parseArchive($ns_server->{'id'}, $ns_server->{'localhost'}, $opt_s);
        } else {
            parseLogFile($ns_server->{'id'}, $ns_server->{'localhost'}, $previous_launch_time);
        }
    }
    $sth2->finish();
}

clean_exit("Done.\n");
