#!/usr/bin/env python

import re
import os
import sys
from distutils.core import setup
from distutils.command.install import install as _install
from distutils.errors import DistutilsOptionError, DistutilsFileError

def findFiveDir(home):
    """Search the $INSTANCE_HOME/Products/ directory for a Five product, if
    its not found, check in $SOFTWARE_HOME/Products/"""
    
    fiveDir = os.path.join(home, 'Products', 'Five')
    if os.path.exists(fiveDir):
        return fiveDir
    
    zopeConf = os.path.join(home, 'etc', 'zope.conf')
    f = open(zopeConf)
    for line in f:
        m = re.search(' *\%define *ZOPE *(.*)', line)
        if m:
            zopeDir = m.group(1).strip()
            fiveDir = os.path.join(zopeDir, 'lib', 'python', 'Products', 'Five')
            break
    f.close()

    if os.path.exists(fiveDir):
        return fiveDir

    raise DistutilsFileError("Couldn't find the Five product, make sure you " \
                             "install Five into '%s'" \
                             % os.path.join(home, 'Products'))

def ensureSiteSkel(home):
    """Checks to see if the appropriate site.zcml exists in $INSTANCE_HOME/etc
    and if not it creates it based on the closest Five one it can find."""
    
    packageIncludes = os.path.join(home, 'etc', 'package-includes')
    if not os.path.isdir(packageIncludes):
        print "Creating directory '%s'" % packageIncludes
        os.makedirs(packageIncludes)

    site = os.path.join(home, 'etc', 'site.zcml')
    if not os.path.isfile(site):
        fiveDir = findFiveDir(home)
        skelDir = os.path.join(fiveDir, 'skel')
        skelSite = os.path.join(skelDir, 'site.zcml')
        fin = open(skelSite)
        fout = open(site, 'w')
        fout.write(fin.read())
        fout.close()
        fin.close()
        
        print "Created '%s' based on '%s'" % (site, skelSite)

class Installer(_install):
    def run(self):
        if not self.home:
            raise DistutilsOptionError("Must provide the --home option " \
                                       "(ie setup.py --home /path/to/" \
                                       "instance_home")
        packageIncludes = os.path.join(self.home, 'etc', 'package-includes')
        ensureSiteSkel(self.home)

        slug = os.path.join(packageIncludes, 'pythonproducts-meta.zcml')
        if not os.path.isfile(slug):
            f = open(slug, 'w')
            print >> f, '<include package="Products.pythonproducts" file="meta.zcml" />'
            f.close()

        here = os.path.dirname(sys.argv[0]) or "."
        pkg = os.path.join(here, 'src', 'pythonproducts')
        
        productDir = os.path.join(self.home, 'Products', 'pythonproducts')
        if not os.path.isdir(productDir):
            print "Creating directory '%s'" % productDir
            os.makedirs(productDir)
            
        for x in os.listdir(pkg):
            pkgFile = os.path.join(pkg, x)
            if os.path.isfile(pkgFile):
                fin = open(pkgFile, 'rb')
                fout = open(os.path.join(productDir, x), 'wb')
                fout.write(fin.read())
                fout.close()
                fin.close()

        libDir = os.path.join(self.home, 'lib', 'python')
        if not os.path.isdir(libDir):
            print "Creating directory '%s'" % libDir
            os.makedirs(libDir)
            
        print "pythonproducts successfully installed at '%s'" % self.home


setup(cmdclass={'install': Installer},
      name='pythonproducts',
      version='1.0beta2',
      description='A mechanism to construct Zope 2 products as regular '
                  'python packages',
      author='Rocky Burt',
      author_email='rocky@serverzen.com',
      url='http://codespeak.net/svn/z3/pythonproducts/',
      package_dir={'': 'src'},
      packages=['pythonproducts'])
