#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack LLC.
# 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.

"""
Upload an image into Glance

Usage
=====

    Machine - Kernel outside of the image
    -------------------------------------

        glance-upload --type=kernel <filename> <name>
        glance-upload --type=ramdisk <filename> <name>
        glance-upload --type=machine --kernel=KERNEL_ID --ramdisk=RAMDISK_ID \
                         <filename> <name>

    Raw - Kernel inside, raw image data
    -----------------------------------

        glance-upload --type=raw --kernel=nokernel --ramdisk=noramdisk \
                         <filename> <name>


    VHD - Kernel inside, data encoded with VHD format
    -------------------------------------------------

        glance-upload --type=vhd --kernel=nokernel --ramdisk=noramdisk \
                         <filename> <name>
"""

# FIXME(sirp): This can be merged into glance-admin when that becomes
# available
import argparse
import gettext
import pprint
import os
import sys

# If ../glance/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                   os.pardir,
                                   os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')):
    sys.path.insert(0, possible_topdir)

gettext.install('glance', unicode=1)

from glance.client import Client
from glance.registry.db.api import DISK_FORMATS, CONTAINER_FORMATS


def die(msg):
    print >> sys.stderr, msg
    sys.exit(1)


def parse_args():
    parser = argparse.ArgumentParser(description='Upload an image into Glance')
    parser.add_argument('filename', help='file to upload into Glance')
    parser.add_argument('name', help='name of image')
    parser.add_argument('--host', metavar='HOST', default='127.0.0.1',
               help='Location of Glance Server (default: %(default)s)')
    parser.add_argument('--port', metavar='PORT', type=int, default=9292,
               help='Port of Glance Server (default: %(default)s)')
    parser.add_argument('--type', metavar='TYPE', default='raw',
               help='Type of Image [kernel, ramdisk, machine, raw] '
                    '(default: %(default)s)')
    parser.add_argument('--disk-format', metavar='DISK_FORMAT', default=None,
               choices=DISK_FORMATS,
               help='Disk format of Image [%s] '
                    '(default: %%(default)s)' % ','.join(DISK_FORMATS))
    parser.add_argument('--container-format', metavar='CONTAINER_FORMAT',
               default=None, choices=CONTAINER_FORMATS,
               help='Disk format of Image [%s] '
                    '(default: %%(default)s)' % ','.join(CONTAINER_FORMATS))
    parser.add_argument('--kernel', metavar='KERNEL',
               help='ID of kernel associated with this machine image')
    parser.add_argument('--ramdisk', metavar='RAMDISK',
               help='ID of ramdisk associated with this machine '
                    'image')
    args = parser.parse_args()
    return args


def main():
    args = parse_args()
    meta = {'name': args.name,
            'is_public': True,
            'properties': {}}

    if args.kernel:
        meta['properties']['kernel_id'] = args.kernel

    if args.ramdisk:
        meta['properties']['ramdisk_id'] = args.ramdisk

    if args.type:
        meta['properties']['type'] = args.type

    if args.disk_format:
        meta['disk_format'] = args.disk_format

    if args.container_format:
        meta['container_format'] = args.container_format

    client = Client(args.host, args.port)
    with open(args.filename) as f:
        try:
            new_meta = client.add_image(meta, f)
        except Exception, e:
            print "Failed to add new image. Got error: %s" % e
            return 1

    print 'Stored image. Got identifier: %s' % pprint.pformat(new_meta)


if __name__ == "__main__":
    main()
