#! /usr/bin/env python
"""
cleanup.

Cleanup duplicate file between buckets.
"""

if __name__ == '__main__':
    import sys
    import argparse as ap
    from boto.s3.connection import S3Connection

    from aws_keys import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY

    parser = ap.ArgumentParser(
        prog='cleanup',
        conflict_handler='resolve',
        description='Cleanup duplicate file between buckets.')
    group1 = parser.add_argument_group('Options', '')
    group1.add_argument('--original_file', metavar="STR", type=str,
                        required=True, help='Original file to be removed.')
    group1.add_argument('--final_file', metavar="STR", type=str, required=True,
                        help='Final file to be tested.')
    group1.add_argument('--original_bucket', metavar="STR", type=str,
                        required=True, help='Bucket of original file.')
    group1.add_argument('--final_bucket', metavar="STR", type=str,
                        required=True, help='Bucket of final file.')
    group1.add_argument('-h', '--help', action='help',
                        help='Show this help message and exit')

    if len(sys.argv) == 1:
        parser.print_usage()
        sys.exit(1)

    args = parser.parse_args()

    conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
    original_bucket = conn.get_bucket(args.original_bucket)
    final_bucket = conn.get_bucket(args.final_bucket)

    # Get key file
    original_key = original_bucket.get_key(args.original_file)
    final_key = final_bucket.get_key(args.final_file)

    if original_key and final_key:
        if original_key.etag[1:-1] == final_key.etag[1:-1]:
            print "Deleting original file {0} from bucket {1}".format(
                args.original_file,
                args.original_bucket
            )
            original_key.delete()
        else:
            if original_key.size == final_key.size:
                print "Deleting original file {0} from bucket {1}".format(
                    args.original_file,
                    args.original_bucket
                )
                original_key.delete()
            else:
                print "etags and size do not match, exiting..."
    else:
        print "Unable to locate files..."
