#!/usr/bin/perl

use strict;
use warnings;

my $DRY_RUN = 1;

if ( defined $ARGV[0] && $ARGV[0] eq "--run" ) {
$DRY_RUN = 0;
}

sub find_bin($) {
my $bin_name = shift;
my $bin_path = `which $bin_name`;
chomp $bin_path;
if ( ! defined $bin_path || $bin_path eq "" ) {
print("Couldn't find $bin_name\n");
exit 1;
}

return $bin_path;
}

my $RBIN = find_bin("rclone");

my $RPATH = "spw-b2:spw01Backups1/spwbk-site-backups/";

my $DBIN = find_bin("date");

my $DATE = `$DBIN +%Y%m%d`;
chomp $DATE;

foreach my $file ( split("\n", `$RBIN ls $RPATH | awk \'{print \$2}\'`) ) {
if ( $file =~ m/bk_([0-9]{4}-[0-9]{2}-[0-9]{2})/ ) {
my $file_date = $1;
$file_date =~ tr/-//d;
if ( $file_date < $DATE ) {
my $cmd = "$RBIN delete $RPATH$file";
print("$cmd\n");
if ( $DRY_RUN eq 0 ) {
system($cmd) == 0 or die
"Failed to delete $file, exiting...\n";
}
}
}
}