#!/usr/bin/python
# -*- coding: utf-8 -*-

# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Eucalyptus Systems, Inc.
# All rights reserved.
#
# 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.
#
# Author: Neil Soman neil@eucalyptus.com

import sys
from euca2ools import Euca2ool, Util, InstanceValidationError, \
    ConnectionFailed
import base64
from datetime import datetime, timedelta

usage_string = \
    """
Bundle a Windows instance.

euca-bundle-instance instance_id -b, --bucket bucket -p, --prefix prefix -o access_key_id [-c policy] -w secret_key [-h, --help] [--version] [--debug]

REQUIRED PARAMETERS

instance_id			Identifier of the instance to be bundled.

-b, --bucket 			The name of the bucket to upload to. Bucket will be created if it does not exist.

-p, --prefix			The prefix for the image file name.

-o, --user-access-key-id	Access Key ID of the owner of the bucket.

-c, --policy			Base64 encoded upload policy that defines upload permissions and conditions. 
				If no policy is specified, a default policy is generated.

-w, --user-secret-key		Secret key used to sign the upload policy.

-x, --expires			Expiration for the generated upload policy (hours).

OPTIONAL PARAMETERS

"""


def usage(status=1):
    print usage_string
    Util().usage()
    sys.exit(status)


def version():
    print Util().version()
    sys.exit()


def display_bundle(bundle):
    bundle_string = '%s\t%s\t%s\t%s\t%s\t%s\t%s' % (
        bundle.id,
        bundle.instance_id,
        bundle.bucket,
        bundle.prefix,
        bundle.state,
        bundle.start_time,
        bundle.update_time,
        )
    print 'BUNDLE\t%s' % bundle_string


def generate_default_policy(
    bucket,
    prefix,
    expiration,
    acl,
    ):
    delta = timedelta(hours=expiration)
    expiration_time = (datetime.utcnow() + delta).replace(microsecond=0)
    expiration_str = expiration_time.isoformat()

    policy = '{"expiration": "%s",' % expiration_str \
        + '"conditions": [' + '{"bucket": "%s" },' % bucket \
        + '{"acl": "%s" },' % acl + '["starts-with", "$key", "%s"]' \
        % prefix + ']' + '}'
    encoded_policy = base64.b64encode(policy)
    return encoded_policy


def main():
    euca = None
    try:
        euca = Euca2ool('b:p:o:c:w:x:', [
            'bucket=',
            'prefix=',
            'policy=',
            'user-access-key-id=',
            'user-secret-key=',
            'expires=',
            ])
    except Exception, e:
        print e
        usage()

    bucket = None
    prefix = None
    access_key_id = None
    policy = None
    secret_key = None
    instance_id = None
    expiration = 24

    for (name, value) in euca.opts:
        if name in ('-b', '--bucket'):
            bucket = value
        elif name in ('-p', '--prefix'):
            prefix = value
        elif name in ('-o', '--user-access-key-id'):
            access_key_id = value
        elif name in ('-c', '--policy'):
            policy = value
        elif name in ('-w', '--user-secret-key'):
            secret_key = value
        elif name in ('-x', '--expires'):
            try:
                expiration = int(value)
                if expiration < 0:
                    print 'Expiration needs to be > 0.'
                    sys.exit(1)
            except ValueError:
                print 'Expiration must be an integer value.'
                sys.exit(1)
        elif name in ('-h', '--help'):
            usage(0)
        elif name == '--version':
            version()

    for arg in euca.args:
        instance_id = arg
        break

    if instance_id and bucket and prefix and access_key_id \
        and secret_key:
        try:
            euca.validate_instance_id(instance_id)
        except InstanceValidationError:
            print 'Invalid instance id'
            sys.exit(1)
        try:
            euca_conn = euca.make_connection()
        except ConnectionFailed, e:
            print e.message
            sys.exit(1)
        if not policy:
            policy = generate_default_policy(bucket, prefix,
                    expiration, 'ec2-bundle-read')
        try:
            bundle_task = \
                euca_conn.bundle_instance(instance_id=instance_id,
                    s3_bucket=bucket, s3_prefix=prefix,
                    s3_upload_policy=policy)
        except Exception, ex:
            euca.display_error_and_exit('%s' % ex)

        if bundle_task:
            display_bundle(bundle_task)
    else:
        if not instance_id:
            print 'instance_id must be specified.'
        if not bucket:
            print 'bucket must be specified.'
        if not prefix:
            print 'prefix must be specified.'
        if not access_key_id:
            print 'access_key_id must be specified.'
        if not secret_key:
            print 'secret_key must be specified.'
        usage(1)


if __name__ == '__main__':
    main()

