#!/usr/bin/perl

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

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

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::Session;
use Orchard::AWS::Credential;

my ( $opt, $usage ) = clopt(
    [ 'profile|p=s' => 'AWS Profile to use for creds default:prod', { 'default'  => 'prod' } ],
    [ 'cluster|c=s' => 'Cluster name to get logs from :requrired',  { 'required' => 1 } ],
    [ 'help|?|h'    => "print usage message and exit" ]
);

eval {
    my $p = Orchard::AWS::Credential->getProfile( $opt->profile );
    die if not defined $p;
    my $emr      = "aws emr --profile " . $p->profile;
    my $clusters = awscmd("$emr list-clusters --active");
    my $clusterId;
    foreach my $c ( @{ $clusters->{'Clusters'} } ) {
        $clusterId = $c->{'Id'} if ( $c->{'Name'} = $opt->cluster );
        last if $clusterId;
    }
    my $desc = awscmd("$emr describe-cluster --cluster-id $clusterId");
    if ( defined $desc ) {
        my $logPath = $desc->{'Cluster'}->{'LogUri'} . $clusterId;
        $logPath =~ s/s3n/s3/;
        my $listing = awscmd( "aws s3 ls $logPath --profile " . $p->profile, "no-decode" );
        my $x;
    }
};
if ($@) {
    my $e;
}

sub awscmd {
    my $cmd = shift;
    my $nod = shift;
    my $out = runcmd($cmd);
    if ( $out->[1] ) {
        logMessage( 'error', "$out->[2]" );
        exit;
    }
    my $output;
    if ( defined $nod ) {
        $output = $out->[0];
    } else {
        $output = JSON::XS::decode_json( $out->[0] );
    }
    $output;

}

__END__
   'Clusters' => ARRAY(0x7f834c79a070)
      0  HASH(0x7f834c79a238)
         'Id' => 'j-3PQ11QL986U'
         'Name' => 'qa-royalties-cluster'
         'NormalizedInstanceHours' => 672
         'Status' => HASH(0x7f834c79a0a0)
            'State' => 'WAITING'
            'StateChangeReason' => HASH(0x7f834c79a370)
               'Message' => 'Cluster ready to run steps.'
            'Timeline' => HASH(0x7f834c799f20)
               'CreationDateTime' => 1619024936.3
               'ReadyDateTime' => 1619025451.82
      1  HASH(0x7f834c79a3e8)
         'Id' => 'j-3B4YMQRYEJOH8'
         'Name' => 'qa-abacus-compute-test-cluster'
         'NormalizedInstanceHours' => 9360
         'Status' => HASH(0x7f834c79a148)
            'State' => 'WAITING'
            'StateChangeReason' => HASH(0x7f834c7a9b50)
               'Message' => 'Cluster ready to run steps.'
            'Timeline' => HASH(0x7f834c79a058)
               'CreationDateTime' => 1617722550.923
               'ReadyDateTime' => 1617723076.413
