# -*- coding: utf-8 -*-

"""
Usage example

Most basic
    fab -H penguin-diver@qyp

Little bit complex
    fab -H penguin-diver@qyp input-pipeline-install --version='0.0.4'
"""
from fabric import task
from os.path import join as path_join
from textwrap import dedent
from datacloud.key_manager.key_helpers import get_key
from datacloud.input_pipeline.input_pipeline.settings import BasicPipelineSettings

USER = 'penguin-diver'
GIT_REPO = 'https://github.yandex-team.ru/x-products/xprod-input-pipeline'
COMMON_DIR = '/srv/common'
YT_DOCKER_REPO = 'https://github.yandex-team.ru/yt/docker.git'
DOCKER_REGISTRY = 'registry.yandex.net'
SECRETS_FILE = BasicPipelineSettings.SECRETS_FILE
DOCKER_TOKEN_NAME = 'DOCKER_TOKEN'


@task
def uninstall_docker(c):
    print('--- removing docker')
    c.sudo('apt-get remove docker docker-engine docker.io')
    c.sudo('apt-get purge docker-ce')
    c.sudo('rm -rf /var/lib/docker')
    print('--- removed docker')


@task
def setup_docker(c):
    print('--- start setup docker')
    c.sudo('apt-get install -y apt-transport-https ca-certificates curl software-properties-common')
    c.run('curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -')
    c.sudo('add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"')
    c.sudo('apt-get update')
    c.run('apt-cache policy docker-ce')
    c.sudo('apt install -y docker-ce')
    c.sudo('usermod -aG docker ${USER}')
    print('--- done setup docker')


@task
def update(c):
    c.sudo('apt-get update')


@task
def setup_pip(c):
    c.run('mkdir -p ~/.pip')
    c.run('touch ~/.pip/pip.conf')
    with open('yreps.txt', 'r') as yreps:
        c.sudo('echo "{}" > ~/.pip/pip.conf'.format(yreps.read()))


@task
def make_common_dir(c):
    c.sudo('mkdir -p {}'.format(COMMON_DIR))
    c.sudo('chmod 777 {}'.format(COMMON_DIR))


@task
def input_pipeline_install(c, version=None):
    input_pipeline_dir = path_join(COMMON_DIR, GIT_REPO.split('/')[-1])
    c.run('rm -rf {}'.format(input_pipeline_dir))
    c.run('git clone {} {}'.format(GIT_REPO, input_pipeline_dir))
    if version is not None:
        with c.cd(input_pipeline_dir):
            c.run('pwd')
            c.run('git checkout tags/v{}'.format(version))

    requirements_path = path_join(input_pipeline_dir, 'requirements.txt')
    c.sudo('pip install -r {}'.format(requirements_path))
    c.sudo('pip install -e {}'.format(input_pipeline_dir))


def get_docker_key(docker_key=None):
    if docker_key is None:
            docker_key = get_key(SECRETS_FILE, DOCKER_TOKEN_NAME, default=None)
    assert docker_key is not None, 'Docker key should be provided!'

    return docker_key


@task
def docker_stop_all(c):
    c.run('docker stop $(docker ps -a -q) || true')
    c.run('docker rm $(docker ps -a -q) || true')
    c.run('docker system prune -a -f')


@task
def setup_local_yt(c, docker_key=None):
    docker_key = get_docker_key(docker_key)
    docker_stop_all(c)
    local_yt_dir = path_join(COMMON_DIR, 'local_yt')
    c.run('rm -rf {}'.format(local_yt_dir))
    c.run('git clone {} {}'.format(YT_DOCKER_REPO, local_yt_dir))
    c.run('docker login -u {} -p {} {}'.format(USER, docker_key, DOCKER_REGISTRY))
    c.run('{}/run_local_cluster.sh'.format(local_yt_dir))


@task
def install_jupyter(c):
    print('--- start setup jupyter')
    c.sudo('pip install ipython==5.7')
    c.sudo('pip install tornado==5.1.1')
    c.sudo('pip install ipykernel==4.10')
    c.sudo('pip install notebook==5.6.0')
    c.sudo('pip install jupyter-client==5.2.3')
    c.sudo('pip install jupyter-console==5.2.0')
    c.sudo('pip install jupyter-core==4.4.0')
    c.sudo('pip install jupyter==1.0.0')

    jupyter_folder = '~/.jupyter/'
    jupyter_counfig_file = path_join(jupyter_folder, 'jupyter_notebook_config.py')
    c.sudo('rm -rf {path}'.format(path=jupyter_counfig_file))
    c.run('jupyter notebook --generate-config')

    config = dedent("""\
        c.NotebookApp.ip = '*'
        c.NotebookApp.open_browser = False
        c.NotebookApp.port = 9999""")

    c.run('echo "{config}" >> {path}'.format(config=config, path=jupyter_counfig_file))
    print('--- done setup jupyter')


@task(default=True)
def raskatiska(c, user=USER, version=None, docker_key=None):
    print('Raskatka began...')
    docker_key = get_docker_key(docker_key)

    if docker_key is None:
        docker_key = get_key(SECRETS_FILE, DOCKER_TOKEN_NAME, default=None)
    assert docker_key is not None, 'Docker key should be provided!'

    update(c)
    uninstall_docker(c)
    setup_docker(c)
    make_common_dir(c)
    setup_pip(c)
    input_pipeline_install(c, version=version)
    setup_local_yt(c, docker_key=docker_key)
    install_jupyter(c)
