from fabric.api import env, local, put, run, lcd, task, prefix, sudo
from fabric.contrib.files import exists, append, upload_template
from fabric.colors import green
import tempfile
import shutil
import os
import settings

current_path = os.path.dirname(os.path.realpath(__file__))

def __init():
    if not env.get('temp_folder', None):
        env['temp_folder'] = tempfile.mkdtemp()
        print(green("working folder is %s" % env['temp_folder']))

def __clean():
    if env.get('temp_folder', None):
        print(green("Removing %s" % env['temp_folder']))
        shutil.rmtree(env['temp_folder'])

def get_version_path():
    return os.path.join(env['temp_folder'], env['version'])

def export():
    local('hg archive -r %s %s' % (env['version'], get_version_path()) )

def pack():
    # create a new source distribution as tarball
    with lcd(os.path.join(get_version_path(),env.source_rel_path)):
        local('python setup.py sdist --formats=gztar', capture=False)

def create_virtualenv():
    with lcd(os.path.join(get_version_path(),env.source_rel_path)):
        tmpd = run('mktemp -d').strip()
        put('virtualenv/*.txt', tmpd)
        run('virtualenv -p %s %s' % (env.srv_python_location,env.srv_venv_path))
        with prefix('source %s/bin/activate' % env.srv_venv_path):
            run('pip install -r %s/requirements.txt' % tmpd)
            run('pip install -r %s/requirements_srvr.txt' % tmpd)
        with prefix('source %s/bin/activate' % env.srv_venv_path):
            site_package_location = run('python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"').strip()
            upload_template(os.path.join(current_path,'config_path.pth'), os.path.join(site_package_location,'config_path.pth'),context={"srv_config_path": env.srv_config_path})

        append(os.path.join(env.srv_venv_path, "bin/activate"), "export DJANGO_SETTINGS_MODULE="+env.srv_django_settings_module)

        run('rm -fr %s' % tmpd)


def deploy():
    # figure out the release name and version
    with lcd(os.path.join(get_version_path(),env.source_rel_path)):
        dist = local('python setup.py --fullname', capture=True).strip()
        print(green("dist is %s" % dist))

        # upload the source tarball to the temporary folder on the server
        put('dist/%s.tar.gz' % dist, '/tmp/%s.tar.gz' % dist)
        # create a place where we can unzip the tarball, then enter
        # that directory and unzip it
        # now setup the package with our virtual environment's
        # python interpreter
        with prefix('source %s/bin/activate' % env.srv_venv_path):
            run('pip install -U --force-reinstall /tmp/%s.tar.gz' % dist)
        # now that all is set up, delete the folder again

        run('rm -rf /tmp/%s.tar.gz' % dist)
        sudo(env.srv_restart_cmd, shell=False)

@task(default=True)
def deploy_version(version='tip'):
    env['version'] = version
    __init()
    export()
    pack()
    if not exists(env.srv_venv_path):
        create_virtualenv()
    deploy()
    __clean()
