import os
import shutil
import tempfile
from fabric.api import (
    local,
    settings,
    ) 
from fabric.utils import abort
from hashlib import sha1

def ensure_virtualenv(virtualenvs_path='.virtualenvs',
                      virtualenv_symlink='virtualenv'):
    # Check the SHA1 hash of the requirements.txt and see if the
    # corresponding virtual env already exists, if not create it.
    with open('requirements.txt', 'r') as requirements:
        digest = sha1(requirements.read()).hexdigest()                                                                

    real_virtualenvs_path = os.path.realpath(virtualenvs_path)
    venv_matching_requirements = os.path.join(real_virtualenvs_path, 'goaltracker_' + digest)
    if not os.path.exists(venv_matching_requirements):
        print("No matching virtualenv found. Creating one now.")
        local("virtualenv " + venv_matching_requirements, capture=False)
        with settings(warn_only=True):
            result = local("/usr/bin/pip install -E {0} -r requirements.txt".format(
                venv_matching_requirements), capture=True)
        if result.failed:
            shutil.rmtree(venv_matching_requirements)
            abort("Failed to install requirements. Deleted incomplete virtualenv.")                                   

    # If the virtualenv symlink already points to the correct
    # virtual env, we can just return.
    if os.path.lexists(virtualenv_symlink):
        if os.path.realpath(virtualenv_symlink) == venv_matching_requirements:
            print("The current {0} symlink matches the current "
                  "requiremens.txt.".format(virtualenv_symlink))
            return virtualenv_symlink
        os.remove(virtualenv_symlink)                                                                                 

    print("Creating a {0} symlink pointing to virtualenv matching the "
          "current requirements.txt.".format(virtualenv_symlink))
    local('ln -s {0} {1}'.format(venv_matching_requirements, virtualenv_symlink), capture=False)
    return virtualenv_symlink