def main(args, logger):
    if args.region:
        regions = [args.region]
    else:
        regions = get_regions()
    results = {'Low': 0, 'Medium': 0, 'High': 0}
    with open(args.filename, 'w') as csvoutfile:
        writer = csv.writer(csvoutfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow(CSV_HEADER)
        for r in regions:
            macie_client = boto3.client('macie2', region_name=r)
            findingCriteria = {'criterion': {'category': {'eq': ['CLASSIFICATION']}}}
            if args.bucket:
                findingCriteria['criterion']['resourcesAffected.s3Bucket.name'] = {'eq': [args.bucket]}
            if args.severity:
                if (args.severity == 'High'):
                    findingCriteria['criterion']['severity.description'] = {'eq': ['High']}
                elif (args.severity == 'Medium'):
                    findingCriteria['criterion']['severity.description'] = {'eq': ['High', 'Medium']}
                else:
                    pass
            if args.since:
                end_time = datetime.now()
                start_time = datetime.strptime(args.since, '%Y-%m-%d')
                findingCriteria['criterion']['createdAt'] = {'gte': (int(start_time.timestamp()) * 1000), 'lte': (int(end_time.timestamp()) * 1000)}
            logger.debug(f'findingCriteria: {json.dumps(findingCriteria, indent=2)}')
            list_response = macie_client.list_findings(findingCriteria=findingCriteria, maxResults=40)
            findings = list_response['findingIds']
            logger.debug(f'Found {len(findings)} findings in {r}')
            if (len(findings) == 0):
                continue
            get_response = macie_client.get_findings(findingIds=findings)
            for f in get_response['findings']:
                bucket_name = f['resourcesAffected']['s3Bucket']['name']
                key = f['resourcesAffected']['s3Object']['key']
                (summary, count) = get_summary(f)
                obj_publicAccess = 'Unknown'
                if ('publicAccess' in f['resourcesAffected']['s3Object']):
                    obj_publicAccess = f['resourcesAffected']['s3Object']['publicAccess']
                writer.writerow([f['accountId'], bucket_name, r, f['resourcesAffected']['s3Object']['extension'], f['severity']['description'], f['type'], count, summary, key, f's3://{bucket_name}/{key}', f'https://{bucket_name}.s3.amazonaws.com/{key}', f"https://{r}.console.aws.amazon.com/macie/home?region={r}#findings?search=resourcesAffected.s3Bucket.name%3D{bucket_name}&macros=current&itemId={f['id']}", f['createdAt'], obj_publicAccess])
                results[f['severity']['description']] += 1
            while ('nextToken' in list_response):
                sleep(0.5)
                list_response = macie_client.list_findings(findingCriteria=findingCriteria, maxResults=40, nextToken=list_response['nextToken'])
                findings = list_response['findingIds']
                logger.debug(f'Found {len(findings)} more findings in {r}')
                get_response = macie_client.get_findings(findingIds=findings)
                for f in get_response['findings']:
                    bucket_name = f['resourcesAffected']['s3Bucket']['name']
                    key = f['resourcesAffected']['s3Object']['key']
                    (summary, count) = get_summary(f)
                    obj_publicAccess = 'Unknown'
                    if ('publicAccess' in f['resourcesAffected']['s3Object']):
                        obj_publicAccess = f['resourcesAffected']['s3Object']['publicAccess']
                    writer.writerow([f['accountId'], bucket_name, r, f['resourcesAffected']['s3Object']['extension'], f['severity']['description'], f['type'], count, summary, key, f's3://{bucket_name}/{key}', f'https://{bucket_name}.s3.amazonaws.com/{key}', f"https://{r}.console.aws.amazon.com/macie/home?region={r}#findings?search=resourcesAffected.s3Bucket.name%3D{bucket_name}&macros=current&itemId={f['id']}", f['createdAt'], obj_publicAccess])
                    results[f['severity']['description']] += 1
    print(f"Exported High: {results['High']} Medium: {results['Medium']} Low: {results['Low']} ")
    csvoutfile.close()
def main(args, logger):
    if args.region:
        regions = [args.region]
    else:
        regions = get_regions()
    results = {'Low': 0, 'Medium': 0, 'High': 0}
    with open(args.filename, 'w') as csvoutfile:
        writer = csv.writer(csvoutfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow(CSV_HEADER)
        for r in regions:
            macie_client = boto3.client('macie2', region_name=r)
            findingCriteria = {'criterion': {'category': {'eq': ['CLASSIFICATION']}}}
            if args.bucket:
                findingCriteria['criterion']['resourcesAffected.s3Bucket.name'] = {'eq': [args.bucket]}
            if args.severity:
                if (args.severity == 'High'):
                    findingCriteria['criterion']['severity.description'] = {'eq': ['High']}
                elif (args.severity == 'Medium'):
                    findingCriteria['criterion']['severity.description'] = {'eq': ['High', 'Medium']}
                else:
                    pass
            if args.since:
                end_time = datetime.now()
                start_time = datetime.strptime(args.since, '%Y-%m-%d')
                findingCriteria['criterion']['createdAt'] = {'gte': (int(start_time.timestamp()) * 1000), 'lte': (int(end_time.timestamp()) * 1000)}
            logger.debug(f'findingCriteria: {json.dumps(findingCriteria, indent=2)}')
            list_response = macie_client.list_findings(findingCriteria=findingCriteria, maxResults=40)
            findings = list_response['findingIds']
            logger.debug(f'Found {len(findings)} findings in {r}')
            if (len(findings) == 0):
                continue
            get_response = macie_client.get_findings(findingIds=findings)
            for f in get_response['findings']:
                bucket_name = f['resourcesAffected']['s3Bucket']['name']
                key = f['resourcesAffected']['s3Object']['key']
                (summary, count) = get_summary(f)
                obj_publicAccess = 'Unknown'
                if ('publicAccess' in f['resourcesAffected']['s3Object']):
                    obj_publicAccess = f['resourcesAffected']['s3Object']['publicAccess']
                writer.writerow([f['accountId'], bucket_name, r, f['resourcesAffected']['s3Object']['extension'], f['severity']['description'], f['type'], count, summary, key, f's3://{bucket_name}/{key}', f'https://{bucket_name}.s3.amazonaws.com/{key}', f"https://{r}.console.aws.amazon.com/macie/home?region={r}#findings?search=resourcesAffected.s3Bucket.name%3D{bucket_name}&macros=current&itemId={f['id']}", f['createdAt'], obj_publicAccess])
                results[f['severity']['description']] += 1
            while ('nextToken' in list_response):
                sleep(0.5)
                list_response = macie_client.list_findings(findingCriteria=findingCriteria, maxResults=40, nextToken=list_response['nextToken'])
                findings = list_response['findingIds']
                logger.debug(f'Found {len(findings)} more findings in {r}')
                get_response = macie_client.get_findings(findingIds=findings)
                for f in get_response['findings']:
                    bucket_name = f['resourcesAffected']['s3Bucket']['name']
                    key = f['resourcesAffected']['s3Object']['key']
                    (summary, count) = get_summary(f)
                    obj_publicAccess = 'Unknown'
                    if ('publicAccess' in f['resourcesAffected']['s3Object']):
                        obj_publicAccess = f['resourcesAffected']['s3Object']['publicAccess']
                    writer.writerow([f['accountId'], bucket_name, r, f['resourcesAffected']['s3Object']['extension'], f['severity']['description'], f['type'], count, summary, key, f's3://{bucket_name}/{key}', f'https://{bucket_name}.s3.amazonaws.com/{key}', f"https://{r}.console.aws.amazon.com/macie/home?region={r}#findings?search=resourcesAffected.s3Bucket.name%3D{bucket_name}&macros=current&itemId={f['id']}", f['createdAt'], obj_publicAccess])
                    results[f['severity']['description']] += 1
    print(f"Exported High: {results['High']} Medium: {results['Medium']} Low: {results['Low']} ")
    csvoutfile.close()