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

    Takes a prepared Machine Configuration and carries out the necessary steps in the cloud before you will be able to
    launch it (e.g. provision a machine, apply any configuration, install services, and take a snapshot).

    Usage:
        prepare MACHINE_SPEC

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

"""

import sys
import time

import docopt

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


def create_droplet(manager, config_path):
    return manager.first_boot(
        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']
    env = environment.build_environment()
    manager = cloud.initialize_cloud(env.cloud_config)

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

    with UncertainProgressBar('Awaiting power down...') as p:
        while not droplet.is_powered_down():
            p.tick()
            time.sleep(2)

    snapshot_name, action = droplet.snapshot()
    with UncertainProgressBar('Taking droplet snapshot...') as p:
        while not action.is_finished():
            p.tick()
            time.sleep(2)

    with UncertainProgressBar('Tearing down base image...') as p:
        droplet.delete()

    print('Droplet preparation finished - snapshot saved as {}'.format(snapshot_name))


if __name__ == '__main__':
    main()
