#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.config

from fabric.api import run, prefix, env
from fabric.context_managers import cd, shell_env
from fabric.tasks import Task


logging.config.fileConfig('logging.conf')
logger = logging.getLogger('general')

env.user = 'root'


class BaseTaskMixin(object):
    def set_host(self, host_string):
        logger.info('Setting configugration...')
        env.host_string = host_string
        logger.info('Host: %s', str(env.host_string))


class DeployBaseTask(Task, BaseTaskMixin):
    """
    Update deployment server to new project version from git repo (abstract class)
    """
    name = 'deploy'
    PROJECT_PATH = '/home/ordergroup/sites/pname'
    VIRTUALENV_ACTIVATE = 'source /home/ordergroup/venvs/pname/bin/activate'

    def run(self, branch='dev', db_env='dev', install_req=False):
        logger.info('Starting deployment...')
        with shell_env(DJANGO_DATABASE=db_env):
            with cd(self.PROJECT_PATH):
                logger.info('Updating from repo...')
                git_res = run('git pull origin %s' % (branch, ))
                logger.info('Git result:\n%s', git_res)
                logger.info('Cleaning pyc files...')
                pyc_res = run('find . -name "*.pyc" -exec rm -rf {} \;')
                logger.info('Cleaning result:\n%s', pyc_res)
                with prefix(self.VIRTUALENV_ACTIVATE):
                    if install_req:
                        logger.info('Installing req...')
                        req_result = run('pip install -r req')
                        logger.info('Installing req result:\n%s', req_result)
                    logger.info('Collecting static...')
                    collect_res = run('python manage.py collectstatic --noinput')
                    logger.info('Collect static result:\n%s', collect_res)
                    logger.info('Migrating database...')
                    migrate_res = run('python manage.py migrate')
                    logger.info('Migration result:\n%s', migrate_res)
                logger.info('Granting permissions to logs directory...')
                chmod_res = run('chmod -R 777 logs')
                logger.info('Granting permissions result:\n%s', chmod_res)
                logger.info('Restarting popojutrze gunicorn...')
                apache_res = run('service gunicorn-popojutrze restart')
                logger.info('Restart result:\n%s', apache_res)
