#!/usr/bin/perl

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

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

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

my $s3path  = 's3://orchard-transfers/catalog-deliveries';
my $listing = 'aws s3 --profile=orch\-transfer ls ' . $s3path . '/|grep PRE|sed \'s/^  *PRE //g\'|sort -n';
print "$listing\n";

my $out = Common::RunCommand::execute($listing,1);
my $files = [ split "\n", $out->[0] ];

foreach my $file ( @{$files} ) {
    next unless $file =~ m/.*_.*/;
    my ( $id, $path ) = split '_', $file;
    my $old = "$s3path/$file";
    my $new = "$s3path/$id/";
    my $cmd = "aws s3 --profile=orch\-transfer sync \"$old\" \"$new\"";
    print "$cmd\n";
    system($cmd);
}
