###RUN_PERL: #!/usr/bin/perl

# oldlogs is generated from oldlogs.1.pl.
#
# This script renames log files if they are big enough.
# Compresses or removes older log files.
#
# Copyright (C) 2015, 2016, 2023  Balthasar Szczepański
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


###PERL_GZIP:              GZIP              = gzip
###PERL_LOG_PATH:          LOG_PATH          = /botm/log/bsta/
###PERL_LOG_SIZE_LIMIT:    LOG_SIZE_LIMIT    = 65536
###PERL_LOGS_UNCOMPRESSED: LOGS_UNCOMPRESSED = 2
###PERL_LOGS_TOTAL:        LOGS_TOTAL        = 10


if ($ARGV[0] ne '') {
	$log_path = $ARGV[0];
}
else {
	$log_path = LOG_PATH;
}
if ($ARGV[1] =~ /^([0-9]+)$/) {
	$log_size_limit = $1;
}
else {
	$log_size_limit = LOG_SIZE_LIMIT;
}
if ($ARGV[2] =~ /^([0-9]+)$/) {
	$logs_total = $1;
}
else {
	$logs_total = LOGS_TOTAL;
}
if ($ARGV[3] =~ /^([0-9]+)$/) {
	$logs_uncompressed = $1;
}
else {
	$logs_uncompressed = LOGS_UNCOMPRESSED;
}

if ( opendir ($dir, $log_path)) {
	while ($subpath = readdir $dir) {
		if ($subpath !~ /\.log$/) {
			next;
		}
		$fullpath=$log_path.$subpath;
		unless (-f $fullpath) {
			next;
		}
		unless (@stat = stat($fullpath)) {
			next;
		}
		if ($stat[7] > $log_size_limit) {
			movelog($fullpath,0,0);
		}
		
	}
	closedir($dir);
}

sub movelog {
	(my $path, my $number, my $gz) = @_;
	my $nextgz = 0;
	my $thispath;
	my $nextpath;
	my $nextnumber=$number+1;
	my @gzip_arg = (GZIP, '-q', '-9','-f');
	
	$thispath = $path.(($number != 0)?'.'.$number.($gz?'.gz':''):'');
	if ($number == $logs_total) {
		if (unlink $thispath) {
			return 1;
		}
		else {
			return 0;
		}
	}
	if ($number == $logs_uncompressed) {
		$nextgz=1;
		$nextpath = $path.'.'.$nextnumber.'.gz';
	}
	else {
		$nextpath = $path.'.'.$nextnumber.($gz?'.gz':'');
	}
	
	if (-e $nextpath) {
		unless (movelog($path,$nextnumber,($nextgz or $gz)?1:0)) {
			return 0;
		}
	}
	
	if ($nextgz) {
		push @gzip_arg, $thispath;
		unless (! system (@gzip_arg)) {
			return 0;
		}
		$thispath .= '.gz';
	}
	
	unless (rename ($thispath, $nextpath)) {
		return 0;
	}
	return 1;
}
