#!/usr/bin/env python

"""Usage:
    nebula login
    nebula get <service> <plan> <platform> [<location>]
    nebula status <service_id>
    nebula restart <service_id>
    nebula destroy <service_id>
    nebula list [--all]

    Use Nebula to provision and manipulate various services.

    Supported services:
        PostgreSQL Database

    Supported Platforms:
        Digital Ocean  digital-ocean
        Rackspace      rackspace
        Linode         linode
        AWS            aws

    Choosing Data Centers [<location>]:
        Digital Ocean: NY1, NY2, AM1, AM2, SF1, SP1 (defaults to AM1)
        Rasckspace: DFW, ORD, IAD, SYD, HGK (defaults to Northern Virginia)
        Linode: Not supported yet (defaults to Newark)
        AWS: Not supported yet (defaults to Northern Virginia)

    Options:
      -h --help     Lists help
      -v --verbose  More verbose output of commands
"""
from docopt import docopt

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    import logging
    logging.basicConfig(format='%(message)s', level=logging.INFO)

    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

    from nebula.api import (get_service, get_service_status, login, destroy_service,
        list_services)
    from nebula.conf import PLATFORMS

    # Disable requests logging
    logging.getLogger("requests").propagate = False

    log = logging.getLogger(__name__)

    arguments = docopt(__doc__)
    if arguments.get('get'):

        platform = arguments.get('<platform>')
        if platform not in PLATFORMS:
            log.error('ERROR: Available keywords for platforms are: ')
            for p in PLATFORMS:
                log.info(p)
            sys.exit(1)

        service = arguments.get('<service>')
        plan = arguments.get('<plan>')
        location = arguments.get('<location>')
        service_id = get_service(service, plan, platform, location)
        log.info('Please wait while we set up your service')
        get_service_status(service_id, retry=True)

    if arguments.get('status'):
        service_id = arguments.get('<service_id>')
        get_service_status(service_id)

    if arguments.get('login'):
        login()

    if arguments.get('destroy'):
        log.info("===This action is not reversible and will destroy all you data.===")
        try:
            input = raw_input
        except NameError:
            pass
        confirm = input("To confirm please type in the word DESTROY: ")
        if confirm.lower().strip() != 'destroy':
            log.info('Confirmation not received. Aborting...')
            sys.exit(1)
        service_id = arguments.get('<service_id>')
        destroy_service(service_id)

    if arguments.get('list'):
        list_services(all=arguments.get('--all'))
