#!/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:

Raw:

    glance-upload <filename> <name>

Kernel-outside:

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

"""
import argparse
import pprint
import sys

from glance.client import Client


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: 127.0.0.1)')
    parser.add_argument('--type', metavar='TYPE', default='raw',
                        help='Type of Image [kernel, ramdisk, machine, raw] '
                             '(default: raw)')
    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, 'type': args.type, 'is_public': True}

    if args.type == 'machine':
        if args.kernel and args.ramdisk:
            meta['properties'] = {'kernel_id': args.kernel,
                                  'ramdisk_id': args.ramdisk}
        else:
            die("kernel and ramdisk required for machine image")

    client = Client(args.host, 9292)
    with open(args.filename) as f:
        new_meta = client.add_image(meta, f)

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


if __name__ == "__main__":
    main()
