#! /usr/bin/env python3
# coding=utf-8
"""
    crumhorn machine launch

    Launches a pre-prepared box, from a MACHINE_SPEC. Prints out the new box's IP when it's ready.

    Usage:
    launch MACHINE_SPEC

    Arguments:
    MACHINE_SPEC        The file containing a prepared Machine Spec (usually generated by a crumhorn compile step)

"""
import os
import sys
import time

import docopt

import crumhorn.configuration.machineconfiguration as machineconfiguration
from crumhorn.backends.digitalocean import cloud
from . import UncertainProgressBar


def launch_droplet(manager, config_path):
    return manager.launch(
        machine_configuration=machineconfiguration.load_configuration(config_path),
        size_slug='512mb')


def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    options = docopt.docopt(__doc__, argv=argv)
    configuration = options['MACHINE_SPEC']

    manager = cloud.initialize_cloud(os.environ)

    with UncertainProgressBar('Creating droplet...') as p:
        droplet = launch_droplet(manager, configuration)
        while not droplet.is_up():
            p.tick()
            time.sleep(2)

    print('Droplet created: {ip}'.format(ip=droplet.ip))


if __name__ == '__main__':
    main()
