#!/usr/bin/python

import argparse, sys
try:
    import boto3
except ImportError, ie:
    print "ImportError for boto3, please install boto3 via `sudo easy_install pip; sudo pip install boto3`"
    sys.exit(1)

'''
StageName refers to the CodeBuild stage in raid/pipeline/primary-pipeline.yaml
Operations are idempotent, disabled stage won't error if disabled again
'''
def toggle_code_freeze(client, pipeline, freeze=True):
    try:
        if freeze:
            client.disable_stage_transition(
                pipelineName=pipeline,
                stageName='Build',
                transitionType='Outbound',
                reason='Code freeze was called'
            )
        else:
            client.enable_stage_transition(
                pipelineName=pipeline,
                stageName='Build',
                transitionType='Outbound'
            )
    except Exception as e:
        print e
        return False

    return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument('pipeline', type=str,
                        help='Name of the AWS CodePipeline to toggle')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-f', action='store_true', help='Enable code freeze')
    group.add_argument('-u', action='store_false', help='Disable code freeze')
    parser.add_argument('-r', '--region', type=str,
                        help='AWS Region which contains the CodePipeline')

    args = parser.parse_args()

    if args.region:
        client = boto3.client('codepipeline', region_name=args.region)
    else:
        client = boto3.client('codepipeline')

    success = toggle_code_freeze(client, args.pipeline, freeze=args.f)

    action = 'freeze' if args.f else 'unfreeze'
    result = 'Successfully performed the' if success else 'Failed to toggle'

    print '%s %s' % (result, action)
