#! /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/trunk/centreon/bin/logAnalyser $
# SVN : $Id: logAnalyser 13900 2012-12-05 14:43:41Z anguyen $
#
####################################################################################

# 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_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-cbroker.log";

my %svc_status_code = (
    "OK"       => 0,
    "WARNING"  => 1,
    "CRITICAL" => 2,
    "UNKNOWN"  => 3
);
my %host_status_code = (
    "UP"            => 0,
    "DOWN"          => 1,
    "UNREACHABLE"   => 2,
    "PENDING"       => 4
);
my %type_code = (
    "SOFT" => 0,
    "HARD" => 1
);

my ($dbh, $dbhoreon) = (undef, undef);
my $appID = undef;
my $msg_type5_disabled = 0;
my $cpt = 0;
my $ctime = 0;
my $retention = undef;
my $current_time = time();
my $retention_time;
my %cache_host_service = ();
my %cache_host = ();

# 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 clean_exit()

Enforce a proper exit in every case.

=cut
sub clean_exit {
    my $message = shift;
    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time());

    print "$mday/" . ($mon + 1) . "/" . ($year + 1900) . " $hour:$min:$sec -  $message";

    if (defined $dbhoreon) {
        $dbhoreon->disconnect();
    }
    if (defined $dbh) {
        $dbh->disconnect();
    }
    exit 0;
}

# Get poller id from poller name
sub getPollerId($) {
    my $instanceName = $_[0];

    my $sth = $dbhoreon->prepare("SELECT id 
			          FROM nagios_server 
                                  WHERE name = ".$dbhoreon->quote($instanceName)." 
                                  AND ns_activate = '1'");
    die "Error:" . $sth->errstr . "\n" if (!$sth->execute);
    while ((my $row = $sth->fetchrow_hashref())) {
        return $row->{'id'};
    }
    return 0;
}

# Parsing .log
sub parseFile($$) {
    my $instance_name = $_[1];
    my $logFile = $_[0];
        
    # Open Log File for parsing
    if (!open (FILE, $_[0])){
        writeLogFile("Cannot open file : $_[0]");
        return;
    }

    #
    # Now Read unknown log lines
    #
    while (<FILE>) {
	# If ctime too new. Out
	if ($_ =~ m/^\[([0-9]*)\]/ && ($1 > $current_time || $1 < $retention_time)) {
		next;
	}
		
        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;
            $tab[5] =~ s/\\/\\\\/g; 
            $tab[5] =~ s/\'/\\\'/g;
	    next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'}));
            my $rq = "INSERT INTO `logs` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `type`, `retry`, `output`, `instance_name`, `host_id`, `service_id`) VALUES ('0', '$ctime', '".$tab[0]."', '".$tab[1]."', '". $svc_status_code{$tab[2]} ."', '". $type_code{$tab[3]} ."','".$tab[4]."','".$tab[5]."', '".$instance_name."', '" . $cache_host{$tab[0]} . "', '" . $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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;
            }
	    next if (!defined($cache_host{$tab[0]}));
            my $rq = "INSERT INTO `logs` (`msg_type`,`ctime`, `host_name` , `status`,  `type`, `retry`, `output`, `instance_name`, `host_id`) VALUES ('1', '$ctime', '".$tab[0]."', '". $host_status_code{$tab[1]} ."', '". $type_code{$tab[2]} ."','".$tab[3]."','".$tab[4]."', '".$instance_name."', '" . $cache_host{$tab[0]} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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] = "";
            }
	    next if (!defined($cache_host_service{$tab[1] . ":" . $tab[2]}->{'service_id'}));
            my $rq = "INSERT INTO `logs` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `notification_cmd`, `notification_contact`, `output`, `instance_name`, `host_id`, `service_id`) VALUES ('2', '$ctime', '".$tab[1]."', '".$tab[2]."', '". $svc_status_code{$tab[3]} ."', '".$tab[4]."','".$tab[0]."','".$tab[5]."', '".$instance_name."', '" . $cache_host{$tab[1]} . "', '" .  $cache_host_service{$tab[1] . ":" . $tab[2]}->{'service_id'} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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] = "";
            }
	    next if (!defined($cache_host{$tab[1]}));
            my $rq = "INSERT INTO `logs` (`msg_type`,`ctime`, `notification_contact`, `host_name` , `status`, `notification_cmd`,  `output`, `instance_name`, `host_id`) VALUES ('3', '$ctime', '".$tab[0]."','".$tab[1]."', '". $host_status_code{$tab[2]} ."', '".$tab[3]."','".$tab[4]."', '".$instance_name."', '" .  $cache_host{$tab[1]} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
                    $tab[0] =~ s/\'/\\\'/g;
	    next if (!defined($cache_host{$tab[0]}));
            my $rq = "INSERT INTO `logs` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance_name`, `host_id`) VALUES ('7', '$ctime', '".$tab[0]."', '". $host_status_code{$tab[1]} ."', '". $type_code{$tab[2]} ."', '".$instance_name."', '" .  $cache_host{$tab[0]} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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;
	    next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'}));
            my $rq = "INSERT INTO `logs` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance_name`, `host_id`, `service_id`) VALUES ('6', '$ctime', '".$tab[0]."', '".$tab[1]."', '". $svc_status_code{$tab[2]} ."', '". $type_code{$tab[3]} ."', '".$instance_name."', '" .  $cache_host{$tab[0]} . "', '" . $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/){
            my @tab = split(/;/, $2);
            $ctime = $1;
            $tab[0] =~ s/\\/\\\\/g;
                    $tab[0] =~ s/\'/\\\'/g;
	    next if (!defined($cache_host{$tab[0]}));
            my $rq = "INSERT INTO `logs` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance_name`, `host_id`) VALUES ('9', '$ctime', '".$tab[0]."', '". $host_status_code{$tab[1]} ."', '". $type_code{$tab[2]} ."', '".$instance_name."', '" . $cache_host{$tab[0]} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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;
	    next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'}));
            my $rq = "INSERT INTO `logs` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance_name`, `host_id`, `service_id`) VALUES ('8', '$ctime', '".$tab[0]."', '".$tab[1]."', '". $svc_status_code{$tab[2]} ."', '". $type_code{$tab[3]} ."', '".$instance_name."', '" . $cache_host{$tab[0]} . "', '" . $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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;
	    next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'}));
            my $rq = "INSERT INTO `logs` (`msg_type`, `ctime`, `host_name`, `service_description`, `notification_contact`, `output`, `instance_name`, `host_id`, `service_id`) VALUES ('10', '$ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[5]."', '".$tab[6]."','".$instance_name."', '" . $cache_host{$tab[0]} . "', '" . $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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;
	    next if (!defined($cache_host{$tab[0]}));
            my $rq = "INSERT INTO `logs` (`msg_type`, `ctime`, `host_name`, `notification_contact`, `output`, `instance_name`, `host_id`) VALUES ('11', '$ctime', '".$tab[0]."', '".$tab[4]."', '".$tab[5]."','".$instance_name."', '" . $cache_host{$tab[0]} . "')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/){
            my $tab = $2;
            $ctime = $1;
            $tab =~ s/\\/\\\\/g; 
            $tab =~ s/\'/\\\'/g;
            my $rq = "INSERT INTO `logs` (`msg_type`,`ctime`, `output`, `instance_name`) VALUES ('4','$ctime', '".$tab."', '".$instance_name."')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\n");
        } 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 `logs` (`msg_type`,`ctime`, `output`, `instance_name`) VALUES ('5','$ctime', '".$tab."', '".$instance_name."')";
            my $res = $dbh->do($rq) or die("SQL INSERT ERROR :" . $dbh->errstr . "\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 parseArchive($instance)



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

    # Get instance name
    my $sth_server = $dbhoreon->prepare("SELECT localhost, id, name FROM `nagios_server` WHERE id = " . $instance);
    if (!$sth_server->execute) {
	die "Error:" . $sth_server->errstr . "\n";
    }
    my $tmp_server = $sth_server->fetchrow_hashref();

    if ($tmp_server->{'localhost'}) {
        my $sth_varlog = $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_varlog->execute()) {
             clean_exit("Error:" . $sth_varlog->errstr . "\n");
        }
        $data = $sth_varlog->fetchrow_hashref();
        if (!$data->{'log_archive_path'}) {
            clean_exit("Could not find local var log directory\n");    
        }
        $archives = $data->{'log_archive_path'};
        $sth_varlog->finish();
    } else {
        $archives = "$VarLib/log/$instance/archives/";
    }

    my @log_files = split /\s/,`ls $archives`;
    foreach (@log_files) {
	parseFile($archives.$_, $tmp_server->{'name'});
    }
}

=head1 MAIN

Program starts here.

=cut

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

if ($opt_h) {
    print "This script is used for inserting data when there are gaps in the logs. Use this if your system is running with Centreon Broker, otherwise use the logAnalyser script.\n\n";
    print "Usage : $0 :\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;

# 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});

# 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() if (!$data->{'archive_log'});

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

my ($day,$month,$year) = (localtime(time()))[3,4,5];
$retention_time =  mktime(0,0,0,$day-$retention,$month,$year,0,0,-1);

my $res;

# Get cache
my $filter_instance = "";
my $instanceId;
if (defined($opt_p)) {
        $instanceId = getPollerId($opt_p);
        if ($instanceId == 0) {
            clean_exit("Unknown poller $opt_p\n");
        }
	$filter_instance = "ns_host_relation.nagios_server_id = $instanceId AND ";
}

my $sth_cache = $dbhoreon->prepare("SELECT host.host_id, host.host_name FROM host, ns_host_relation WHERE ${filter_instance}ns_host_relation.host_host_id = host.host_id AND host.host_activate = '1'");
die "Error:" . $sth_cache->errstr . "\n" if (!$sth_cache->execute);
while ((my $tmp_cache = $sth_cache->fetchrow_hashref())) {
	$cache_host{$tmp_cache->{'host_name'}} = $tmp_cache->{'host_id'};
}

$sth_cache = $dbhoreon->prepare("SELECT host.host_name, host.host_id, service.service_id, service.service_description FROM host, host_service_relation, service, ns_host_relation WHERE ${filter_instance}ns_host_relation.host_host_id = host.host_id AND host.host_id = host_service_relation.host_host_id AND host_service_relation.service_service_id = service.service_id AND service.service_activate = '1'");   
die "Error:" . $sth_cache->errstr . "\n" if (!$sth_cache->execute);
while ((my $tmp_cache = $sth_cache->fetchrow_hashref())) {
	$cache_host_service{$tmp_cache->{'host_name'} . ':' . $tmp_cache->{'service_description'}} = {'host_id' =>  $tmp_cache->{'host_id'}, 'service_id' =>  $tmp_cache->{'service_id'}};
}

$sth_cache = $dbhoreon->prepare("SELECT host.host_name, host.host_id, service.service_id, service.service_description FROM host, host_service_relation, hostgroup_relation, service, ns_host_relation WHERE ${filter_instance}ns_host_relation.host_host_id = host.host_id AND host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id AND host_service_relation.service_service_id = service.service_id AND service.service_activate = '1'");
die "Error:" . $sth_cache->errstr . "\n" if (!$sth_cache->execute);
while ((my $tmp_cache = $sth_cache->fetchrow_hashref())) {
	$cache_host_service{$tmp_cache->{'host_name'} . ':' . $tmp_cache->{'service_description'}} = {'host_id' =>  $tmp_cache->{'host_id'}, 'service_id' =>  $tmp_cache->{'service_id'}};
}

if (defined($opt_p) && $instanceId) {
    if (!defined $opt_s) {
        $res = $dbh->do("DELETE FROM `logs` WHERE instance_name = '$opt_p' AND `ctime` < $current_time");
        writeLogFile("DELETE FROM `logs` WHERE instance_name = '$opt_p' AND `ctime` < $current_time") if (!defined($res));
    } else {
        my $limit = date_to_time($opt_s);
	if ($limit > $retention_time) {
		$retention_time = $limit;
	}
        $res = $dbh->do("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time");
	writeLogFile("SQL ERROR: DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time") if !defined($res);
    }
    parseArchive($instanceId);
} else {
    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()) {
            if (!defined $opt_s) {
                $res = $dbh->do("DELETE FROM `logs` WHERE `ctime` < $current_time");
                writeLogFile("SQL INSERT ERROR :DELETE FROM `logs` WHERE `ctime` < $current_time") if (!defined($res));
            } else {
                my $limit = date_to_time($opt_s);
		if ($limit > $retention_time) {
			$retention_time = $limit;
		}
                $res = $dbh->do("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time");
                writeLogFile("SQL ERROR: DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time") if !defined($res);
            }
            parseArchive($ns_server->{'id'});
    }
    $sth2->finish();
}

clean_exit("End\n");
