import base64

import boto3

# fetch_credentials exists to allow cross-account access of specific resources.
#
# For instance, suppose this program is being run on account A that hosts DNS
# management, but Cyral's sidecars are hosted in account B. One may provide an
# IAM role from B that allows A access to Secrets Manager in B. In that case,
# the Certificate Manager assumes that role, so that the program will only
# interact with Secrets Manager resources in B.
def fetch_credentials(sm_role_arn):
    creds = None
    if sm_role_arn != '':
        # Assume role to access another account
        sts_client = boto3.client('sts')
        assume_role_resp = sts_client.assume_role(
            RoleArn=sm_role_arn,
            RoleSessionName='cyral_sidecar_certificate_manager',
        )
        creds = assume_role_resp['Credentials']
    return creds

def is_cfn_request(event, request_type=None):
    predicate = 'RequestType' in event.keys()
    if request_type != None:
        predicate = predicate and event['RequestType'] == request_type
    return predicate

def encode_b64_str(s, encoding='ascii'):
    return base64.b64encode(s.encode(encoding)).decode(encoding)

def decode_b64_str(s, encoding='ascii'):
    return base64.b64decode(s.encode(encoding)).decode(encoding)

def result_json(secret_id, status=None, reason=None):
    result = {}
    result['SecretId'] = secret_id
    if status != None:
        result['Status'] = status
    if reason != None:
        result['Reason'] = reason
    return result
