# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""Proxy AMI-related calls from cloud controller to objectstore service."""

import binascii
import os
import shutil
import tarfile
import tempfile
from xml.etree import ElementTree

import boto.s3.connection
import eventlet

from nova import crypto
from nova import exception
from nova import flags
from nova import image
from nova import log as logging
from nova import utils
from nova.image import service
from nova.api.ec2 import ec2utils


LOG = logging.getLogger("nova.image.s3")
FLAGS = flags.FLAGS
flags.DEFINE_string('image_decryption_dir', '/tmp',
                    'parent dir for tempdir used for image decryption')
flags.DEFINE_string('s3_access_key', 'notchecked',
                    'access key to use for s3 server for images')
flags.DEFINE_string('s3_secret_key', 'notchecked',
                    'secret key to use for s3 server for images')


class S3ImageService(service.BaseImageService):
    """Wraps an existing image service to support s3 based register."""

    def __init__(self, service=None, *args, **kwargs):
        self.service = service or image.get_default_image_service()
        self.service.__init__(*args, **kwargs)

    def create(self, context, metadata, data=None):
        """Create an image.

        metadata['properties'] should contain image_location.

        """
        image = self._s3_create(context, metadata)
        return image

    def delete(self, context, image_id):
        self.service.delete(context, image_id)

    def update(self, context, image_id, metadata, data=None):
        image = self.service.update(context, image_id, metadata, data)
        return image

    def index(self, context):
        return self.service.index(context)

    def detail(self, context):
        return self.service.detail(context)

    def show(self, context, image_id):
        return self.service.show(context, image_id)

    def show_by_name(self, context, name):
        return self.service.show_by_name(context, name)

    @staticmethod
    def _conn(context):
        # NOTE(vish): access and secret keys for s3 server are not
        #             checked in nova-objectstore
        access = FLAGS.s3_access_key
        secret = FLAGS.s3_secret_key
        calling = boto.s3.connection.OrdinaryCallingFormat()
        return boto.s3.connection.S3Connection(aws_access_key_id=access,
                                               aws_secret_access_key=secret,
                                               is_secure=False,
                                               calling_format=calling,
                                               port=FLAGS.s3_port,
                                               host=FLAGS.s3_host)

    @staticmethod
    def _download_file(bucket, filename, local_dir):
        key = bucket.get_key(filename)
        local_filename = os.path.join(local_dir, filename)
        key.get_contents_to_filename(local_filename)
        return local_filename

    def _s3_parse_manifest(self, context, metadata, manifest):
        manifest = ElementTree.fromstring(manifest)
        image_format = 'ami'
        image_type = 'machine'

        try:
            kernel_id = manifest.find('machine_configuration/kernel_id').text
            if kernel_id == 'true':