# Copyright 2011-2014 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
#   Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
#
#   Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os.path
import re
import sys
import urlparse

from boto.roboto.awsqueryservice import AWSQueryService, NoCredentialsError
from boto.roboto.awsqueryrequest import AWSQueryRequest
from boto.roboto.param import Param
import boto.utils


__version__ = '4.1.0'


class EC2(AWSQueryService):
    Name = 'ec2'
    Description = 'compute service'
    APIVersion = '2012-07-20'
    Authentication = 'sign-v2'
    Path = '/services/compute'
    Port = 8773
    Provider = 'aws'
    EnvURL = 'EC2_URL'


class EucAdmin(AWSQueryService):

    Name = 'eucadmin'
    Description = 'Eucalyptus Administration Services'
    APIVersion = 'eucalyptus'
    Authentication = 'sign-v2'
    ServicePath = '/services/Configuration'
    Port = 8773
    Provider = 'aws'
    EnvURL = None
    InstallPath = '/'

    def check_for_env_url(self):
        if not self.args.get('url'):
            self.args['url'] = urlparse.urljoin('http://127.0.0.1/',
                                                self.ServicePath)
        AWSQueryService.check_for_env_url(self)

    def handle_error(self, ex):
        s = ""
        if not hasattr(ex,"errors"):
            s = 'ERROR %s' % (ex)
        else:
            if ex.errors.__len__() != 0:
                for i in ex.errors:
                    s = '%sERROR %s %s %s: %s\n' % (s, ex.status,
                                                    ex.reason,
                                                    i[0], i[1])
            else:
                s = 'ERROR %s %s %s' % (ex.status, ex.reason, ex)
            while s.count("\n") != 3:
                s = re.sub(".*Exception.*\n", ": ", s)
        print s.replace("\n","")
        sys.exit(1)


class EucadminRequest(AWSQueryRequest):
    __enabled_debugging = False

    def send(self, verb='GET', **args):
        # We have to handle debug specially because AWSQueryRequest.send gets
        # debug=True it adds another stream logger, resulting in duplicate log
        # messages going to the console when debugging is enabled.
        if 'debug' in args:
            debug = args.pop('debug')
            self.args.pop('debug', None)
        else:
            debug = self.args.pop('debug', 0)
        if EucadminRequest.__enabled_debugging:
            # Debugging is already on; make sure we don't enable it again.
            debug = 0
        elif debug > 0:
            EucadminRequest.__enabled_debugging = True

        try:
            return AWSQueryRequest.send(self, verb=verb, debug=debug, **args)
        except NoCredentialsError:
            # Try local authentication
            if 'EUCALYPTUS' in os.environ:
                euca_home = os.environ['EUCALYPTUS']
            elif os.path.exists(os.path.join(self.ServiceClass.InstallPath,
                                             'var/lib/eucalyptus/keys')):
                # self.ServiceClass.InstallPath is the eucalyptus home
                euca_home = self.ServiceClass.InstallPath
            else:
                # out of ideas
                raise
            url = 'http://localhost:8773/services/Eucalyptus'
            gc_cls = boto.utils.find_class('eucadmin.getcredentials',
                                           'GetCredentials')
            obj = gc_cls(euca_home=euca_home, account='eucalyptus',
                         user='admin', zipfile='notused')
            key_id, secret_key = obj.get_accesskey_secretkey().split('\t')
            args['aws_access_key_id']     = key_id
            args['aws_secret_access_key'] = secret_key
            args['url'] = url
            response = AWSQueryRequest.send(self, verb=verb, **args)
            return response


def print_version_if_necessary():
    """
    If '--version' appears in sys.argv then print the version and exit
    successfully.

    This is a hackish workaround for a roboto limitation in boto 2.1.1.
    """
    if '--version' in sys.argv:
        print 'eucalyptus', __version__
        sys.exit()


class EucaFormat():
    SERVICE_TYPE = ['%-18s']
    PARTITION = ['%-10s']
    SERVICE_NAME = ['%-21s']
    PREFIX = ['%s']
    PREFIX_LINE = PREFIX + SERVICE_TYPE + PARTITION + SERVICE_NAME
    STATE = ['%-8s']
    URI = ['%-35s']
    FULLNAME = ['%-35s']

    def __init__(self):
        pass

