#!/usr/bin/env python

# 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 getopt, sys, os
from euca2ools import Euca2ool, SizeValidationError, SnapshotValidationError, Util

usage_string = """
Creates a volume in a specified availability zone.

euca-create-volume -S, --size size | --snapshot snapshot_id -z zone
[-h, --help] [--version] [--debug]

REQUIRED PARAMETERS	

-s, --size			size of the volume (in GiB). 
	
--snapshot			snapshot id to create the volume from. Either size or snapshot can be specified (not both).
	
-z, --zone 			availability zone to create the volume in
	
OPTIONAL PARAMETERS

"""

version_string = """    euca-create-volume version: 1.0 (BSD)"""

def usage():
    print usage_string
    Util().usage(compat=True)

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

def display_volume(volume):
    if not volume.id:
	return 
    volume_string = '%s' % (volume.id)
    if volume.size:
	volume_string += '\t%d' % (volume.size)
    if volume.snapshot_id:
	    volume_string += '\t%s' % (volume.snapshot_id)
    volume_string += '\t%s\t%s' % (volume.status, volume.create_time)
    print 'VOLUME\t%s' % (volume_string)

def main():
    euca = None
    try:
        euca = Euca2ool('s:z:',
                                   ['zone=', 'snapshot=', 'size='], compat=True)
    except Exception, e:
	print e
        usage()
 
    size = None 
    zone = None
    snapshot_id = None

    for name, value in euca.opts:
        if name in ('-s', '--size'):
	    try:
                size = int(value) 
	    except ValueError:
		print 'Invalid size'
		sys.exit(1)
        elif name in ('-z', '--zone'):
            zone = value 
        elif name == '--snapshot':
            snapshot_id = value 
        elif name in ('-h', '--help'):
            usage()
	elif name == '--version':
	    version()

    euca_conn = euca.make_connection()

    if (size or snapshot_id) and zone:
	if size:
	    try:
	        euca.validate_volume_size(size)
	    except SizeValidationError:
   	        print 'Invalid volume size' 
                sys.exit(1)
	if snapshot_id:
	    try:
	        euca.validate_snapshot_id(snapshot_id)
	    except SnapshotValidationError:
	    	print 'Invalid snapshot id'
		sys.exit(1)

	try:       
	    volume = euca_conn.create_volume(size, zone, snapshot_id)
  	    if volume:
	        display_volume(volume)
	except Exception, ex:
            euca.display_error_and_exit('%s' % ex)

    else:
	if not zone:
    	    print 'availability zone must be specified.'
	if not (size or snapshot_id):
	    print 'size or snapshot id must be specified.'
	usage()
if __name__ == "__main__":
    main()
 
