#!/usr/local/bin/python

import commands, os, os.path, sys
from distutils.core import setup, Extension
from distutils.sysconfig import *
from distutils.errors import *

def get_R_HOME():
    if sys.platform == 'win32':
        import win32api, win32con

        hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE,
                                      "Software\\R-core\\R",
                                      0, win32con.KEY_QUERY_VALUE )
        # get the base directory
        rhome = win32api.RegQueryValueEx( hkey, "InstallPath" )[0]
        win32api.RegCloseKey( hkey )
        return rhome
    else:
        stat, rhome = commands.getstatusoutput('R RHOME')
        if stat:
            raise DistutilsExecError("couldn't execute the R interpreter.\n"
                                 "Check whether R is in the execution path.")
        return rhome

def get_R_SRC():
    rsrc = os.getenv("R_SRC")
    if not rsrc:
        try:
            import readline
        except ImportError:
            pass
        print("R_SRC environment variable was undefined, empty, or was not a directory.")
        rsrc = raw_input("Please enter the path of the R source code: ")

    if rsrc and os.path.isdir(rsrc):
        return rsrc
    else:
        raise DistutilsExecError("Unable to determine path for R source code")
    

# to avoid strict prototypes errors from R includes
get_config_vars()['OPT'] = '-DNDEBUG -g -O3 -Wall'

# get the Python version
if sys.version[:3] == '2.2':
    DEFINE = []
    UNDEF = ['PRE_2_2']
else:
    DEFINE = [('PRE_2_2', None)]
    UNDEF = []

# configure the R paths
RHOME = get_R_HOME()
DEFINE.append(('R_HOME', '"%s"' %RHOME))

r_libs = os.path.join(RHOME, 'bin')
source_files = ["src/rpymodule.c", "src/R_eval.c",
                "src/io.c"]
if sys.platform=='win32':
    RSRC = get_R_SRC()
    include_dirs = [ os.path.join(RHOME.strip(), 'src/include'),
                     os.path.join(RSRC.strip(), 'src/include'), 'src' ]
    libraries=["Rdll","Advapi32"]
    library_dirs = [r_libs, "C:\rpy\bin"]
    extra_compile_args=[]
    source_files = source_files + ["src/setenv.c"]
elif sys.platform=='darwin':
	include_dirs = [ os.path.join(RHOME.strip(), 'include'), 'src' ]
	libraries=['R']
	library_dirs=[os.path.join(RHOME.strip(), 'Frameworks')]
	extra_compile_args=[]
else: # unix-like systems, this is known to work for Linux and Solaris
    include_dirs = [ os.path.join(RHOME.strip(), 'include'), 'src' ]
    libraries=["R"]
    library_dirs = [r_libs]
    extra_compile_args=["-shared"]
    source_files = source_files + ["src/setenv.c"]
    
# check whether Numeric is present
try:
    import Numeric
    DEFINE.append(('WITH_NUMERIC', None))
except ImportError:
    UNDEF.append('WITH_NUMERIC')

# get the RPy version
from rpy_version import rpy_version

LONG_DESC = """RPy provides a robust Python interface to the R
programming language.  It can manage all kinds of R objects and can
execute arbitrary R functions. All the errors from the R language are
converted to Python exceptions."""


setup(name="rpy",
      version=rpy_version,
      description="Python interface to the R language",
      author="Walter Moreira",
      author_email="walterm@cmat.edu.uy",
      url="http://rpy.sourceforge.net",
      license="GPL",
      long_description=LONG_DESC,
      py_modules=['rpy', 'rpy_io', 'rpy_version'],
      ext_modules=[Extension("_rpy",
                             source_files,
                             include_dirs=include_dirs,
                             libraries=libraries,
                             library_dirs=library_dirs,
                             define_macros=DEFINE,
                             undef_macros=UNDEF,
                             extra_compile_args=extra_compile_args,
                             runtime_library_dirs = [r_libs],
                             ),

                   ]
      )


syntax highlighted by Code2HTML, v. 0.9.1