#!/usr/bin/env python3

import boto3
import base64
import argparse
from botocore.exceptions import ClientError


def get_secrets(region, name):

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region
    )
    paginator = client.get_paginator('list_secrets')

    try:
        response_iterator = paginator.paginate(
            Filters=[
                {
                    'Key': 'all',
                    'Values': [ name ]
                },
            ],
            SortOrder='asc',
            PaginationConfig={
                # 'MaxItems': 10,
                'PageSize': 10,
                'StartingToken': None
                }
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'InternalServiceErrorException':
            # An error occurred on the server side.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            # You provided an invalid value for a parameter.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            # You provided a parameter value that is not valid for the current state of the resource.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
            # We can't find the resource that you asked for.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
    else:
        return response_iterator

def list_secrets(args):
    if args.secret:
        output = get_secrets(args.region, args.secret)
        for page in output:
            s = page['SecretList']
            for secrets in s:
                print(secrets['Name'])
    else:
        parser.print_help()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        prog="print_secret", description="Display secrets")
    parser.add_argument('--print', '-p', help="Display secret (default)",
                        action="store_true", default=False)
    parser.add_argument(
        '--region', '-r', help="aws region", default='us-west-2')
    parser.add_argument(
        '--secret', '-s', help="Name of the scret", default=None)

    args = parser.parse_args()
    list_secrets(args)