#!/usr/bin/perl

use constant 'DIR' => '/mnt/mysql/backup/mydumper';

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use DateTime;
use JSON::XS;
use FileHandle;
use File::Find::Rule::DirectoryEmpty;
use Text::CSV::Easy(qw/csv_build csv_parse/);

use lib '/app/tools/common/lib';
use Common::Session;
use Common::Sys::Directory;

my $dryrun = shift @ARGV || 0;

my $directory = Common::Sys::Directory->new();
$directory->path(DIR);
my $files = $directory->sysfiles("*.gz");
foreach my $file ( @{$files} ) {
    if ( $file->daysold < 2 ) {
        logMessage( 'info', $file->path . " is " . $file->daysold . " days old" );
        next;
    } else {
        logMessage( 'warn', "Removing " . $file->path );
        unless ($dryrun) {
            unlink $file->path;
        }
    }
}

## clean any empty directories
my @dirs = File::Find::Rule->directoryempty->in(DIR);
foreach my $dir (@dirs) {
    logMessage( 'info', "Removing empty directory $dir" );
    system("rmdir $dir") unless $dryrun;
}
