#!/usr/bin/env perl

use strict;
use warnings;

use Amazon::API::SecretsManager;
use Amazon::Credentials;
use Data::Dumper;
use English      qw(-no_match_vars);
use Getopt::Long qw(:config no_ignore_case);
use JSON::PP;

########################################################################
sub help {
########################################################################
  print {*STDOUT} <<"END_OF_HELP";

usage: $PROGRAM_NAME options

Options
-------
--help, -h        this
--raw, -r         Dumper output
--json, -j        JSON output
END_OF_HELP

  return 0;
}

########################################################################
sub main {
########################################################################
  my @option_specs = qw(
    help
    raw
    json
  );

  my %options;

  GetOptions( \%options, @option_specs );

  if ( $options{help} ) {
    help();
    return 0;
  }

  my $credentials = Amazon::Credentials->new( no_passkey_warning => 1 );

  my $secrets
    = Amazon::API::SecretsManager->new( credentials => $credentials );

  my $result = $secrets->ListSecrets();

  if ( $options{raw} ) {
    print {*STDOUT} Dumper($result);
  }
  elsif ( $options{json} ) {
    print {*STDOUT} JSON::PP->new->pretty->encode($result);
  }
  else {
    require Text::ASCIITable;

    my $t = Text::ASCIITable->new( { headingText => 'Secrets' } );

    $t->setCols(qw(Name Value Created));

    my $token = eval {
      require IO::Pager;

      IO::Pager::open( *STDOUT, '|-:utf8', 'Unbuffered' );
    };

    if ( ref $result ) {
      my @secrets = @{ $result->{SecretList} };

      foreach (@secrets) {
        my $result = $secrets->GetSecretValue( { SecretId => $_->{Name} } );
        $t->addRow(
          $_->{Name},
          $result->{SecretString},
          $result->{CreatedDate}
        );
      }

      print {*STDOUT} $t;
    }
  }

  return 0;
}

exit main();

1;

__END__
