#!/usr/bin/python

# Copyright (C) 2010 by WooMe.com
# Author: Nic Ferrier, <nferrier@woome.com>

# veh is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# veh is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with veh.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
from ConfigParser import ConfigParser
from os.path import exists as pathexists
from os.path import splitext
from subprocess import Popen

class Exists(Exception):
    """File exists"""
    pass

class ConfigMissing(Exception):
    """File exists"""
    pass


def _popencmd(cmd):
    """Simple Popen wrapper"""
    print " ".join(cmd)
    p = Popen(cmd)
    p.wait()    
    return p

def make_venv(repo):
    """Make a virtualenv for the specified repo"""
    from os.path import expanduser
    # TODO read a user or site wide config file for whether to use virtualenvwrapper
    # could have a "make virtualenv config with a possible 'internal' value"
    _popencmd(["virtualenv", "--no-site-packages", "%s/.venv" % repo])
    with open("%s/.venv/.startup_rc" % repo, "w") as out:
        print >>out, "source %s\nsource %s\n" % (
            expanduser("~/.bashrc"),
            "%s/.venv/bin/activate" % repo
            )


# Packages that we should force easy_install for.
# This should probably be configurable inside veh.
FORCE_EASY_INSTALL = [
    "egenix-mx-base", # see http://bitbucket.org/ianb/pip/issue/40/package-egenix-mx-base-cant-be-installed-with
    ]            

def fill_venv(repo):
    """Install packages into the venv.

    Makes the venv if it needs to."""
    if not pathexists("%s/.venv" % repo):
        make_venv(repo)

    cfgfile = "%s/.veh.conf" % repo
    if not pathexists(cfgfile):
        raise ConfigMissing(cfgfile)

    cfg = ConfigParser()
    cfg.read(cfgfile)

    # Install each package in the venv
    venviron = "%s/.venv" % repo
    packages = cfg.items("packages")
    for package in packages:
        package_name = package[1] or package[0]

        # Check whether pip can't install it.
        if package[0] in FORCE_EASY_INSTALL or package_name in FORCE_EASY_INSTALL:
            ez = _popencmd(["%s/.venv/bin/easy_install" % repo, package_name])
        else:
            # Use pip to install into the venv
            cmd = ["pip", "install", "-E", venviron]
            if (cfg.has_option('pip', 'always-upgrade')
                and cfg.getboolean('pip', 'always-upgrade')):
                cmd.append('--upgrade')
            pip = _popencmd(cmd + [package_name])

def venv(repo):
    """Make the repos venv"""

    venvdir = "%s/.venv" % repo
    if not pathexists(venvdir):
        fill_venv(repo)
    

def edit_file(filename):
    """Open the filename in the editor.

    Actually does the whole pattern of opening a temp file.
    """
    _, extension = splitext(filename)
    from tempfile import mkstemp
    try:
        fd, tempfilename = mkstemp(suffix=".conf", text=True)
        data = CFG_TEMPLATE
        if pathexists(filename):
            with open(filename) as srcfd:
                data = srcfd.read()

        print os.write(fd, data)
        os.close(fd)
    except Exception, e:
        print >>sys.stderr, "problem making temp file: " + str(e)
    else:
        editor = os.environ.get("VISUAL", os.environ.get("EDITOR", "edit"))
        try:
            p = Popen([editor, tempfilename])
            p.wait()
        except Exception, e:
            print >>sys.stderr, "problem running editor"
        else:
            # Copy the temp file in
            if pathexists(filename):
                os.remove(filename)
            os.rename(tempfilename, filename)

CFG_TEMPLATE="""[packages]
# enter package names here like
#   packagelabel = packagename
#
# The package name on the right are passed directly to pip.
# The package label is not used right now.
#
# This makes it easy to use either a pypi name:
#   packagelabel = packagename
# or if the package name is the same as the option label:
#   packagelabel =
#
# or a url:
#   packagelabel = http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.4.9.tar.gz#md5=c49067cab242b5ff8c7b681a5a99533a
#
# or a vc reference:
#   packagelabel = hg+http://domain/repo

[pip]
# supported options for pip:
#   always-upgrade: true
#   supply the --upgrade option to pip when building the virtualenv

# End
"""

def install(repo):
    """Install a veh config file

    Opens VISUAL (and EDITOR if it can't find that) with a template.
    """
    # TODO I think this should commit really. For now, it doesn't.
    # TODO we need to add the line to hgignore for the state file
    cfgfile = "%s/.veh.conf" % repo
    if pathexists(cfgfile):
        raise Exists(cfgfile)
    edit_file(cfgfile)

def edit(repo):
    """Edit the veh config file

    Opens VISUAL on the veh config file."""
    cfgfile = "%s/.veh.conf" % repo
    if pathexists(cfgfile):
        edit_file(cfgfile)
    else:
        print >>sys.stderr, "%s does not exist" % cfgfile


from cmd import Cmd

class SysArgsCmd(Cmd):
    """Let's you use cmd with arg lists"""

    def onecmd(self, args):
        """Make a onecmd that operates on an array"""
        cmdarg = args[0]
        try:
            func = getattr(self, 'do_' + cmdarg)
        except AttributeError:
            return self.default(args[1:])
        else:
            return func(args[1:])

    def do_help(self, arg):
        """A version of help that deals with the array args"""
        return Cmd.do_help(self, " ".join(arg))

class VehCmd(SysArgsCmd):
    repo = None

    def __init__(self, **kwargs):
        from StringIO import StringIO
        Cmd.__init__(self, StringIO())
        self.opts = kwargs

    def _findroot(self):
        import subprocess
        p = subprocess.Popen(["hg", "root"], stdout=subprocess.PIPE)
        p.wait()
        hgroot = p.communicate()[0]
        return hgroot.strip()

    def _getroot(self):
        from os.path import realpath
        from os.path import expanduser
        from os import getcwd
        foundroot = self._findroot()
        root = self.opts.get("root") or foundroot
        return realpath(expanduser(root))

    def do_install(self, arg):
        """Install a virtualenv for the repository.
        Actually installs just the config file. The venv is made on first use.
        """
        install(self._getroot())

    def do_edit(self, arg):
        """Edit the repositorys veh config file.
        Opens VISUAL or EDITOR or /usr/bin/edit on your repositorys config file.
        """
        edit(self._getroot())

    def do_check(self, arg):
        """Report whether the repository has an associated veh.
        """
        root = self._getroot()
        vehenv = "%s/.venv/bin/activate" % root
        if pathexists(vehenv):
            print root
        else:
            return 1

    def do_lspackages(self, arg):
        """List the packages specified in the veh config"""
        
        root = self._getroot()
        cfgfile = "%s/.veh.conf" % root
        if not pathexists(cfgfile):
            raise ConfigMissing(cfgfile)

        cfg = ConfigParser()
        cfg.read(cfgfile)
        for p in cfg.items("packages"):
            print "%s %s" % p

    def do_active(self, arg):
        """Is the virtualenv active? print the path if it is."""
        venv = os.environ.get("VIRTUAL_ENV")
        root = self._getroot()

        if venv == "%s/.venv" % root:
            print venv
        else:
            return 1

    def do_clear(self, arg):
        """Blow away the virtualenv."""
        root = self._getroot()
        # delete the dir
        _popencmd(["rm", "-rf", "%s/.venv" % root])

    def do_rebuild(self, arg):
        """Blow away and rebuild the virtualenv."""
        root = self._getroot()
        # delete the dir
        _popencmd(["rm", "-rf", "%s/.venv" % root])
        # Rebuild it.
        venv(root)

    def do_refresh(self, arg):
        """Refresh all packages"""
        root = self._getroot()
        fill_venv(root)

    def do_shell(self, shellcmd):
        """Start a shell inside the venv'd repository possibly running shellcmd.

        First checks that the virtualenv for the repository has been built and builds
        if necessary.

        Changes directory and spawns the user's SHELL.
        """
        root = self._getroot()
        venv(root)
        command = [os.environ["SHELL"], "--rcfile", "%s/.venv/.startup_rc" % root]
        if shellcmd:
            command += ["-c", " ".join(shellcmd)]
        _popencmd(command)

    def do_noop(self, arg):
        """No-op. Just checks the virtualenv.
        """
        venv(self._getroot())
        

def main():
    from optparse import OptionParser
    p = OptionParser()
    p.add_option(
        "-R",
        "--repository",
        dest="root",
        help="specify the root of the veh protected repository"
        )
    o,a = p.parse_args(sys.argv[1:])

    # Make the processor
    cmdproc = VehCmd(**o.__dict__)

    # Now run the command
    try:
        ret = cmdproc.onecmd(a)
    except IndexError:
        print >>sys.stderr, "not enough arguments. Ask for help ?"
    else:
        if ret:
            sys.exit(ret)



if __name__== "__main__":
    main()

# End
