#!/usr/bin/perl

use constant 'BINLOG_DIR' => '/mnt/mysql/binlog';

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

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

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

## file all mysql.*.99999 files in the binlog dir
my $files;
map { $files->{ File::Basename::basename($_) }++ } File::Find::Rule->file->name(qr/.*mysql.*\.\d+/)->in(BINLOG_DIR);

## ask DB what files should exist
my $dbh = Common::Session::getdbh('localhost');
map {
    my ( $file, $bytes ) = @{$_};
    $files->{$file}--;
} @{ $dbh->selectall_arrayref("show binary logs") };

my $ttl = 0;
foreach my $name ( sort keys %{$files} ) {
    ## if hash key set then remove the file
    if ( $files->{$name} ) {
        my $path = BINLOG_DIR . '/' . $name;
        my $cmd  = "rm -vf $path";
        print "$cmd\n";
        system($cmd);
        $ttl++;
    }
}

print "Complete: $ttl old binlogs removed\n";
