#!/usr/bin/perl

use lib '/scripts';
use strict;
use warnings;

# Copied from Cpanel::Logs.
my @log_locations = qw(
  /var/domlogs               /usr/local/apache/domlogs /usr/local/apache/logs
  /usr/local/apache/var/logs /usr/local/apache/log     /usr/local/apache/var/log
  /etc/httpd/domlogs         /etc/httpd/logs           /etc/httpd/log
);

foreach my $dir (@log_locations) {
    next if !-d $dir;

    opendir( my $dh, $dir ) or next;
    my @logdir_contents = grep { !/^\.\.?$/ } readdir($dh);
    closedir($dh);
    correct_logs( $dir, grep { /^(?:\*|__wildcard__)/ } @logdir_contents );
    foreach my $subdir ( grep { -d "$dir/$_" } @logdir_contents ) {
        my $sdir = "$dir/$subdir";
        opendir( my $dh, $sdir ) or next;
        my @logs = grep { /^(?:\*|__wildcard__)/ } readdir($dh);
        closedir($dh);
        correct_logs( $sdir, @logs );
    }
}

sub correct_logs {
    my ( $dir, @logs ) = @_;

    foreach my $old (@logs) {
        if ( $old =~ /-bytes_log\.offset$/ ) {

            # Get rid of any offset files left by previous incarnations of the code.
            unlink("$dir/$old") or warn "$0: Unable to delete offset file '$dir/$old': $!\n";
            next;
        }
        my $new = $old;
        $new =~ s/^(?:\*|__wildcard__)/_wildcard_/;
        unlink "$dir/old" if -f "$dir/$new";    # remove leftovers, we are writing to new file
        rename( "$dir/$old", "$dir/$new" )
          or warn "$0: Unable to rename '$dir/$old' => '$new': $!\n";
    }
}
