import boto
import argparse
import os
import yaml

"""se_all_buckets.py, 

This module enumerates all buckets available to the provided AWS_ACCESS_KEY_ID && AWS_SECRET_ACCESS_KEY,
and prints out the bucket followed by the ACL returned by get_acl()

Example::
    $python s3_all_buckets_acl.py
    $python s3_all_buckets_acl.py -i AWS_ACCESS_KEY_ID -s AWS_SECRET_ACCESS_KEY

Author:: David Busby <oneiroi@fedoraproject.org>
License:: GPLv3

"""

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument( "-i", 
                         "--access-key-id", 
                         dest="id", 
                         #required=True, 
                         default=os.environ['AWS_ACCESS_KEY_ID'], 
                         help="AWS access key id, defaults to env AWS_ACCESS_KEY_ID")
    parser.add_argument( "-s", 
                         "--secret-access-key", 
                         dest="secret", 
                         #required=True, 
                         default=os.environ['AWS_SECRET_ACCESS_KEY'], 
                         help="AWS access key id, defaults to env AWS_SECRET_ACCESS_KEY")
    
    args        = parser.parse_args()
    conn        = boto.connect_s3(args.id, args.secret)
    buckets     = conn.get_all_buckets()
    buckets_acl = {}
    for bucket in buckets:
        if bucket.name not in buckets_acl:
            buckets_acl.update({ bucket.name: {} })
        grants = bucket.get_acl().acl.grants
        for grant in grants:
            if grant.display_name not in buckets_acl[bucket.name]:
                buckets_acl[bucket.name].update({grant.display_name : []})
            buckets_acl[bucket.name][grant.display_name].append(grant.permission)

    print yaml.safe_dump(buckets_acl, default_flow_style=False)
    #import pdb; pdb.set_trace()

if __name__ == '__main__':
    main()
