#!/usr/bin/env python

import argparse
import yaml
import sys
import os
from ebs_deploy import AwsCredentials, EbsHelper, get, out
from ebs_deploy.commands import get_command, usage


# the commands
def main():
    """
    the main
    """

    # bail if we don't have a command
    if len(sys.argv)<2:
        usage()
        exit(-1)

    # get the command
    command_name = sys.argv[1]

    # setup arguments
    parser = argparse.ArgumentParser(description='Deploy to Amazon Beanstalk', usage='%(prog)s '+command_name+' [options]')
    parser.add_argument('-c', '--config-file', help='Configuration file', default='ebs.config')
    parser.add_argument('-v', '--verbose', help='Enable debug logging', action='store_true')
    command = get_command(command_name)

    # let commands add arguments
    try:
        command.add_arguments(parser)
    except AttributeError:
        pass

    # check for help
    if len(sys.argv) == 3 and sys.argv[2]=='help':
        parser.print_help()
        exit(-1)

    # parse arguments
    args = parser.parse_args(sys.argv[2:])

    # make sure we have an archive or a directory
    if not args.config_file or not os.path.exists(args.config_file):
        out("Config file not found: "+args.config_file)
    	parser.print_help()
    	exit(-1)

    # enable logging
    if args.verbose:
        from boto import set_stream_logger
        set_stream_logger('boto')

    # load config
    #f = open(args.config_file, 'r')
    with open(args.config_file, 'r') as f:
        contents = f.read()
    contents_with_environment_variables_expanded = os.path.expandvars(contents)
    config = yaml.load(contents_with_environment_variables_expanded)

    # create credentials
    aws = AwsCredentials(
        get(config, 'aws.access_key',       os.environ.get('AWS_ACCESS_KEY_ID')),
        get(config, 'aws.secret_key',       os.environ.get('AWS_SECRET_ACCESS_KEY')),
        get(config, 'aws.region',           os.environ.get('AWS_DEFAULT_REGION')),
        get(config, 'aws.bucket',           os.environ.get('AWS_BEANSTALK_BUCKET_NAME')),
        get(config, 'aws.bucket_path',      os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH')))

    # create helper
    helper = EbsHelper(aws, app_name=get(config, 'app.app_name'))

    # execute the command
    exit(command.execute(helper, config, args))
    return


# start the madness
if __name__ == "__main__":
    main()
