#! /usr/bin/env python
#
# This script enables and disables existing object replication. Your account
# and bucket must support this whitelisted feature.
# For now, this script will adjust all rules.

def parse_args():
    "isolated argument parser."
    import argparse
    parser = argparse.ArgumentParser(description="Existing object replication configuration.",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("command", choices=["enable","disable"], help="Command to run. 'enable'|'disable'")
    parser.add_argument("bucket", help="The bucket to work on")
    parser.add_argument("--no-op", "-n", dest="do_it", action="store_false")
    return parser.parse_args()

def set_existing_crr(command, bucket, do_it):
    "Set the existing object cross region replication enabled or disabled."
    import boto3
    import pprint
    s3 = boto3.client("s3")
    rc = s3.get_bucket_replication(Bucket=bucket)["ReplicationConfiguration"]
    pprint.pprint(rc)
    enable = True
    if command == "disable":
        enable = False
    for rule in rc["Rules"]:
        rule["ExistingObjectReplication"] = {"Status": ("Disabled", "Enabled")[enable]}
    #pprint.pprint(rc)
    import json
    print(json.dumps(rc))
    if do_it:
        s3.put_bucket_replication(Bucket=bucket, ReplicationConfiguration=rc)
    print("{} {} existing object replication for '{}'.".format(("Simulated","Done")[do_it],
                                                              ("disabling","enabling")[int(enable)],
                                                              bucket))

def main():
    "Main entry point"
    args = parse_args()
    set_existing_crr(args.command, args.bucket, args.do_it)

if __name__ == '__main__':
    main()
