#!/usr/bin/perl

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

use File::Basename;
use File::Find::Rule;
use Capture::Tiny ':all';
use DateTime::Format::MySQL;

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

use lib '/app/tools/admin/lib';
use Admin::BMan;

my ( $opt, $usage ) = clopt(
    [ 'backupdir|b=s' => 'Backup directory - default in config file' ],
    [ 'dryrun|d'      => 'Dryrun of the backup - STDOUT only' ],
    [ 'force|F'       => 'Force S3 copy' ],
    [ 'schema|s=s'    => 'Schema to backup' ],
    [ 'verbose|v'     => 'Verbose' ],
    [ 'help|?|h'      => "print usage message and exit" ]
);

if ( $opt->help ) {
    print $usage->text . "\n";
    exit 1;
}

$opt->{'verbose'} = 1 if $opt->dryrun;
$opt->{'schema'} = uc( $opt->schema ) if defined $opt->schema;

my $bman = Admin::BMan->new($opt);

eval {
    my $conf   = $bman->config;
    my $bdir   = $opt->backupdir || $conf->backupdir;
    my $bucket = $conf->s3bucket;
    my @files  = File::Find::Rule->file->name('*.gz')->in($bdir);

    foreach my $file ( sort @files ) {
        my $dirname  = File::Basename::dirname($file);
        my $dirsplit = [ split '/', $file ];
        my $basename = pop @{$dirsplit};
        my $schema   = pop @{$dirsplit};
        my $date     = pop @{$dirsplit};

        next if not $schema =~ m/^C_|^BP_|^RSCOM/;

        if ( defined $opt->schema ) {
            next unless $schema eq uc( $opt->schema );
        }

        my $transferred = "$dirname/.${basename}.transferred";
        if ( not $opt->{'force'} and -e $transferred ) {
            $bman->logtext( "$transferred file exists use --force to resend", "error" );
        } else {
            my $dest = join '/', ( $bucket, $schema, $date, $basename );
            my $cmd = "aws s3 cp $file $dest --only-show-errors";

            $bman->logtext("Sending $basename to S3 for $schema @ $date");
            unless ( $bman->execute($cmd) ) {
                $bman->execute("touch $transferred");
            }
        }
    }

    $bman->finish;
};
if ($@) {
    $bman->logtext( $@, 'error' );
    $bman->finish;
    exit 1;
}
