#!/usr/bin/python
'''
get a new ami given a running instance 
'''

import datetime
import logging
import sys
import time

import bellatrix
from bellatrix.lib.ec2_lib import Ec2lib
from bellatrix.lib import bellatrix_util
from bellatrix.lib import util


class Run():
    def __init__(self, key, sec, app_name):
        self.WAIT = 30 
        self._ec2 = Ec2lib(key, sec) 
        self._app_name = app_name
        self.out_file = bellatrix_util.getOutFile(__file__)
        

    def burnInstance(self, instance, config_name):
        config_name = config_name + "-" + datetime.datetime.now().isoformat()
        new_ami = self._ec2.createImage(instance, config_name, "generated by " 
                                        + self._app_name)
        logging.info("ami: %s is being generated. Name: %s" 
                     % (new_ami, config_name))
        util.writeFile(self.out_file, new_ami + "," + config_name)
        return new_ami
    
    def amiIsReady(self, ami_name):
        ready = False
        exceptions = 5
        while not ready:
            try:
                ami = self._ec2.getImage(ami_name)
                logging.info("ami state %s" % ami.state)
                ready = (ami.state == bellatrix.AMI_AVAILABLE)
            except:
                #we will swallow the exception a number of times 
                #since the image object might not be ready at the beginning
                exceptions -= 1
                if exceptions < 1:
                    raise Exception("""Error getting information from image: %s. """
                                    """Please check if you have access or if the image name is correct.""" 
                                    % ami_name)
            if not ready:
                logging.info("AMI:%s is not ready yet. Retrying in %s seconds.... " % (ami_name, self.WAIT))
                time.sleep(self.WAIT)

        logging.info("AMI: %s is ready to use!" % ami_name)

def run(instance, config_name, wait):
    r = Run(bellatrix_util.getKey(), bellatrix_util.getSecret(), bellatrix.APP)
    new_ami = r.burnInstance(instance, config_name)
    if wait:
        r.amiIsReady(new_ami)
    return 0

if __name__ == '__main__':
    sys.exit(run(*sys.argv[1:])) 

