#!/usr/bin/env python
#
#   ConVirt   -  Copyright (c) 2008 Convirture Corp.
#   ======
#
# ConVirt is a Virtualization management tool with a graphical user
# interface that allows for performing the standard set of VM operations
# (start, stop, pause, kill, shutdown, reboot, snapshot, etc...). It
# also attempts to simplify various aspects of VM lifecycle management.
#
#
# This software is subject to the GNU General Public License, Version 2 (GPLv2)
# and for details, please consult it at:
#
#    http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
# 
#
#

import sys
import traceback
import convirt.core.utils.utils
from convirt.core.model.ManagedNode import ManagedNode
from convirt.core.model.GridManager import GridManager
from convirt.core.model.ImageStore import ImageStore
from convirt.core.model.PlatformRegistry import PlatformRegistry
from convirt.core.utils.utils import XMConfig
from convirt.core.utils.constants import *

utils = convirt.core.utils.utils

print len(sys.argv), sys.argv

if len(sys.argv) < 3:
    print "Usage : add_image.py <image_name> <platform> <image_group>"
    sys.exit(0)

local_node = ManagedNode(hostname = LOCALHOST,
                         isRemote = False,
                         helper = None) #creds_helper)

client_config = local_node.config
store = client_config

ui_context = {}
registry = PlatformRegistry(client_config,store,ui_context)

registry.init_platforms(client_config)


try:
    image_store = ImageStore(local_node.config, registry)
except Exception, ex:
    traceback.print_exc()
    store_location = local_node.config.get(utils.XMConfig.PATHS,
                                           prop_image_store)
    print("Error initializing image store.\n %s \n " % str(ex))
    sys.exit(1)


image_name = sys.argv[1]
image_platform = sys.argv[2]
image_group_name = sys.argv[3]
image_group = None

groups = image_store.get_image_groups()
for g in groups.itervalues():
    if g.get_name() == image_group_name:
        image_group = g
        break

if image_group is None:
    print "Group %s not found." % image_group_name
    sys.exit(1)

image_store.create_image(image_group.get_id(), image_name, image_platform)
image_store._commit()

print "Image added successfully"

        
