import logging, os, zc.buildout, pkg_resources
import sys
from distutils.sysconfig import get_python_version
import shutil

class SmhiDeploy:

    def __init__(self, buildout, name, options):
        self.name, self.options = name, options
        options['path'] = os.path.join(
                              buildout['buildout']['directory'],
                              options['path'],
                              )
        if not os.path.isdir(os.path.dirname(options['path'])):
            logging.getLogger(self.name).error(
                'Cannot create %s. %s is not a directory.',
                options['path'], os.path.dirname(options['path']))
            raise zc.buildout.UserError('Invalid Path')
        
        d_eggs = buildout['buildout'].get('develop')
        d_eggs = [os.path.abspath(e.strip()) for e in d_eggs.split('\n')]
        options['eggs'] = '\n'.join([e for e in d_eggs if e in options['eggs']])
        options['executable'] = buildout['buildout']['executable']
        self.executable = options['executable']
        print options
        
    def install(self):
        old_exe = sys.executable
        print sys.executable
        sys.executable = self.executable
        print sys.executable
        path = self.options['path']
        logging.getLogger(self.name).info(
            'Creating directory %s', os.path.basename(path))
        if not os.path.exists(path):
            os.mkdir(path)
        d_eggs = self.options['eggs']
        d_eggs = [os.path.abspath(e.strip()) for e in d_eggs.split('\n')]

        old_dir = os.getcwd()
        os.chdir(path)

        for degs in d_eggs:
            dir, proj = os.path.split(degs)
            version = pkg_resources.get_distribution(proj).version
            name = pkg_resources.get_distribution(proj).project_name
            dist = pkg_resources.Distribution(
                None, None, name, version,
                get_python_version(),
                pkg_resources.get_platform()
            )
            
            os.chdir(degs)
            install_dir = os.path.join(path, name.upper())
            if not os.path.exists(install_dir):
                os.mkdir(install_dir)
            old_path = sys.path[:]
            sys.path.insert(0, install_dir)
            _run_setup("easy_install",
                       "--install-dir=" + install_dir,
                       "--always-unzip",
                       "--site-dirs=" + install_dir,
                       "--script-dir=" + os.path.join(install_dir, str(dist.egg_name() + ".egg"), "bin"),
                       ".")
            sys.path[:] = old_path
            egg_dir = os.path.join(install_dir, str(dist.egg_name() + ".egg"))
            true_egg_dir = os.path.join(install_dir, str(dist.egg_name()))
            os.rename(egg_dir, true_egg_dir)
            os.chdir(path)
            import tarfile
            tar = tarfile.open(os.path.join(path, str(dist.egg_name()) + ".tar.gz"), "w:gz")
            tar.add(name.upper())
            tar.close()
            
            shutil.rmtree(name.upper())

        os.chdir(old_dir)
        sys.executable = old_exe
        return path


    update=install
        
def _run_setup(*args):
    old_args = sys.argv
    sys.argv = ["setup.py"] + list(args)
    old_path = sys.path[:]
    sys.path.insert(0, os.getcwd())
    __import__('setup')
    del sys.modules['setup']
    sys.argv = old_args
    sys.path[:] = old_path