# Path: py_mina/config.py
# def fetch(key, default_value=None):
#     """
#     Gets and ensures config setting or returns `default_value` if provided
#     """
# 
#     if key in config.keys():
#         return config.get(key)
#     else:
#         if default_value != None:
#             return default_value
#         else:
#             raise Exception('"%s" is not defined' % key)
# 
# def ensure(key):
#     """
#     Ensures presence of config setting. Prevents from running unnecessary commands,
#     before discovering, that config setting is not set
#     """
# 
#     if not key in config.keys():
#         raise Exception('"%s" must be defined' % key)
# 
# def set(key, value):
#     """
#     Sets config setting (updates `fabric3` config if necessary)
#     """
# 
#     if key in config.get('farbric_config_settings'):
#         env.update({ key: value })
#         config.update({ key: value })
#     elif key == 'deploy_to':
#         config.update({
#             'deploy_to': value, 
#             'scm': '/'.join([value, 'scm']), 
#             'shared_path': '/'.join([value, 'shared']), 
#             'current_path': '/'.join([value, 'current']), 
#             'releases_path': '/'.join([value, 'releases']), 
#             'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
#         })
#     else:
#         config.update({ key: value })
# 
# def check_config(required_settings=[]):
#     """
#     Ensures required settings in cofig
#     """
# 
#     try:
#         for setting in required_settings:
#             ensure(setting)
#     except EnsureConfigError:
#         msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
# 
#         raise Exception(msg.format(required_settings, config))  
# 
# Path: py_mina/state.py
# def set(key, value):
# 
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
#     """
#     Creates directory/file and sets proper owner/mode.
#     """
# 
#     chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
#     chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
# 
#     def change_owner(owner_triple):
#         """
#         Changes unix owner/mode
#         """
# 
#         run(chmod_sudo + 'chmod 0755 ' + entity_path)
#         run(chown_sudo + 'chown %s:%s %s' % owner_triple)
# 
# 
#     # 1) Create file/directory
# 
#     if entity_type == 'file':
#         run('touch %s' % entity_path)
#     else:
#         run('mkdir -p %s' % entity_path)
# 
#     # 2) Change owner/mode
# 
#     if protected:
#         protected_owner_user = fetch('protected_owner_user')
#         protected_owner_group = fetch('protected_owner_group')
# 
#         change_owner((protected_owner_user, protected_owner_group, entity_path))
#     else:
#         owner_user = fetch('owner_user', default_value=False)
#         owner_group = fetch('owner_group', default_value=False)
#         
#         if owner_user != False and owner_group != False: 
#             change_owner((owner_user, owner_group, entity_path))
#         else:
#             run(chmod_sudo + 'chmod 0755 ' + entity_path)


import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity
            create_entity(build_path, entity_type='directory', protected=False)


def discover_latest_release():
    """
    Connects to remote server and discovers next release number
    """

    releases_path = fetch('releases_path')

    echo_subtask("Discovering latest release number")

    # Get latest release number
    with settings(hide('warnings'), warn_only=True):
        if run('test -d %s' % releases_path).failed:
            last_release_number = 0
            create_entity(releases_path, entity_type='directory', protected=False)
        else:
            releases_respond = run('ls -1p %s | sed "s/\///g"' % releases_path)
            releases_dirs = list(filter(lambda x: len(x) != 0, releases_respond.split('\r\n')))

            if len(releases_dirs) > 0:
                last_release_number = max(map(lambda x: int(x), releases_dirs)) or 0
            else:
                last_release_number = 0

    release_number = last_release_number + 1

    # Set release info to config 
    set('release_number', release_number)

# Path: py_mina/config.py
# def fetch(key, default_value=None):
#     """
#     Gets and ensures config setting or returns `default_value` if provided
#     """
# 
#     if key in config.keys():
#         return config.get(key)
#     else:
#         if default_value != None:
#             return default_value
#         else:
#             raise Exception('"%s" is not defined' % key)
# 
# def ensure(key):
#     """
#     Ensures presence of config setting. Prevents from running unnecessary commands,
#     before discovering, that config setting is not set
#     """
# 
#     if not key in config.keys():
#         raise Exception('"%s" must be defined' % key)
# 
# def set(key, value):
#     """
#     Sets config setting (updates `fabric3` config if necessary)
#     """
# 
#     if key in config.get('farbric_config_settings'):
#         env.update({ key: value })
#         config.update({ key: value })
#     elif key == 'deploy_to':
#         config.update({
#             'deploy_to': value, 
#             'scm': '/'.join([value, 'scm']), 
#             'shared_path': '/'.join([value, 'shared']), 
#             'current_path': '/'.join([value, 'current']), 
#             'releases_path': '/'.join([value, 'releases']), 
#             'build_to': '/'.join([value, 'tmp', 'build-' + str(time.time())]),
#         })
#     else:
#         config.update({ key: value })
# 
# def check_config(required_settings=[]):
#     """
#     Ensures required settings in cofig
#     """
# 
#     try:
#         for setting in required_settings:
#             ensure(setting)
#     except EnsureConfigError:
#         msg = 'Bad config!\nRequired settings: {0}\nCurrent config: {1}'
# 
#         raise Exception(msg.format(required_settings, config))  
# 
# Path: py_mina/state.py
# def set(key, value):
# 
# Path: py_mina/subtasks/setup.py
# def create_entity(entity_path, entity_type = 'file', protected=False):
#     """
#     Creates directory/file and sets proper owner/mode.
#     """
# 
#     chmod_sudo = 'sudo ' if fetch('sudo_on_chmod') else ''
#     chown_sudo = 'sudo ' if fetch('sudo_on_chown') else ''
# 
#     def change_owner(owner_triple):
#         """
#         Changes unix owner/mode
#         """
# 
#         run(chmod_sudo + 'chmod 0755 ' + entity_path)
#         run(chown_sudo + 'chown %s:%s %s' % owner_triple)
# 
# 
#     # 1) Create file/directory
# 
#     if entity_type == 'file':
#         run('touch %s' % entity_path)
#     else:
#         run('mkdir -p %s' % entity_path)
# 
#     # 2) Change owner/mode
# 
#     if protected:
#         protected_owner_user = fetch('protected_owner_user')
#         protected_owner_group = fetch('protected_owner_group')
# 
#         change_owner((protected_owner_user, protected_owner_group, entity_path))
#     else:
#         owner_user = fetch('owner_user', default_value=False)
#         owner_group = fetch('owner_group', default_value=False)
#         
#         if owner_user != False and owner_group != False: 
#             change_owner((owner_user, owner_group, entity_path))
#         else:
#             run(chmod_sudo + 'chmod 0755 ' + entity_path)


# Path: py_mina/subtasks/deploy.py
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subtasks.setup import create_entity

            create_entity(build_path, entity_type='directory', protected=False)


def discover_latest_release():
    """
    Connects to remote server and discovers next release number
    """

    releases_path = fetch('releases_path')

    echo_subtask("Discovering latest release number")

    # Get latest release number
    with settings(hide('warnings'), warn_only=True):
        if run('test -d %s' % releases_path).failed:
            last_release_number = 0
            create_entity(releases_path, entity_type='directory', protected=False)
        else:
            releases_respond = run('ls -1p %s | sed "s/\///g"' % releases_path)
            releases_dirs = list(filter(lambda x: len(x) != 0, releases_respond.split('\r\n')))

            if len(releases_dirs) > 0:
                last_release_number = max(map(lambda x: int(x), releases_dirs)) or 0
            else:
                last_release_number = 0

    release_number = last_release_number + 1

    # Set release info to config 
    set('release_number', release_number)

    set('release_to', '/'.join([releases_path, str(release_number)]))