import os

from fabric.api import env, task, local, settings

from robe import venv

# robe
env.robe.projects = {'cab': {}}
env.robe.venv.pip_version = '9.0.1'
env.robe.venv.quiet_install = False

env.robe.venv.requirements_file = 'deps/python-main.txt'
env.robe.venv.dev_requirements_file = 'deps/python-dev.txt'

# so i can use bash aliases
env.shell = "/bin/bash -l -i -c"

REGISTRY = 'registry.yandex.net'
REGISTRY_PROJECT = 'tools'
REGISTRY_NAME = 'cab'
REGISTRY_FULL_NAME = '/'.join([REGISTRY, REGISTRY_PROJECT, REGISTRY_NAME])
QLOUD_APP = 'cab'


RELEASER_CMD = (
    'docker run -it --rm -e SSH_AUTH_SOCK=/tmp/ssh.agent '
    '-e QLOUD_API_OAUTH_TOKEN=$QLOUD_API_OAUTH_TOKEN '
    '-v ~/.gitconfig:/root/.gitconfig '
    '-v $PWD:/project '
    'registry.yandex.net/tools/releaser'
)


@task
def build(tag='latest', options='',  dockerfile=''):
    cmd = ' '.join([
        'docker build',
        options,
        '-f ' + dockerfile if dockerfile else '',
        '-t',
        REGISTRY_FULL_NAME + ':' + tag,
        '.',
    ])
    local(cmd)


@task
def build_dev(options=''):
    build(options=options)
    build(dockerfile='dev.Dockerfile', tag='dev', options=options)


@task
def run_dev(
        build_options='',
        run_options='',
        tag='dev',
        run_cmd='cab runserver 0.0.0.0:80'
    ):
    with settings(warn_only=True):
        local('docker rm cab-dev-runserver')
    build_dev(build_options)
    cmd = ' '.join([
        'docker run',
        run_options,
        '-it',
        '--rm',
        '-p8080:80',
        '-v ~/dev/cab:/src/',
        '-e',
        'USER=' + os.environ['USER'],
        '--name=cab-dev-runserver',
        REGISTRY_FULL_NAME + ':' + tag,
        run_cmd,
    ])
    local(cmd)


@task
def run_dev_shell(
        build_options='',
        run_options='',
        tag='dev',
        run_cmd='/bin/bash',
    ):
    build_dev(build_options)
    cmd = ' '.join([
        'docker run',
        run_options,
        '-it',
        '--rm',
        '-e',
        'USER=' + os.environ['USER'],
        REGISTRY_FULL_NAME + ':' + tag,
        run_cmd,
    ])
    local(cmd)


@task
def attach(name='cab-dev-runserver'):
    local(' '.join([
        'docker exec',
        '-it',
        name,
        '/bin/bash',
    ]))



@task
def push(tag):
    cmd = ' '.join([
        'docker push',
        REGISTRY_FULL_NAME + ':' + tag,
    ])
    local(cmd)


@task
def release(skip_tests='no', version='', envs='unstable'):
    if skip_tests == 'no':
        test()

    changelog(version=version)
    new_version = get_last_tag()
    build(tag=new_version)
    push(tag=new_version)
    deploy_sis(envs=envs, tag=new_version)
    gitpush()


@task
def get_last_tag():
    return local('git tag | tail -1', capture=True)


@task
def changelog(version=''):
    cmd = RELEASER_CMD + ' changelog --no-push --yes'
    if version:
        cmd += ' --version=' + version
    local(cmd)


@task
def deploy(envs='unstable', tag=''):
    if not tag:
        tag = get_last_tag()

    cmd = ' '.join([
        RELEASER_CMD,
        ' deploy',
        '--image=' + REGISTRY_NAME,
        '--version=' + tag,
        '--application=' + QLOUD_APP,
        '--components=' + 'backend',
    ])
    envs = envs.split('+')
    for environment in envs:
        local('%s --environment=%s' % (cmd, environment))


@task
def deploy_sis(envs='unstable', tag=''):
    if not tag:
        tag = get_last_tag()
    executable = '~/.pyenv/versions/3.5.1/bin/sis'
    envs = envs.split('+')
    for environment in envs:
        local('%s push tools.cab.%s %s' % (executable, environment, tag))
        print('https://qloud.yandex-team.ru/projects/tools/cab/' + environment)


@task
def gitpush():
    local('git push && git push --tags')


@task
def test(options=''):
    # venv.create()
    with venv.activate():
        local('py.test ' + options)
