#!/usr/bin/env python
"""
install.py

General installation script for the segtools package. Interacts with
the user to configure the environment to download and install all
dependencies and the segtools package.

This script is designed to be downloaded and run independently, and
will guide the process of downloading and installing all other source
code.

(c) 2009: Orion Buske <orion.buske@gmail.com>

XXX: R and necessary R packages are not checked/installed.
XXX: Relatively untested
"""

${COMMON_CODE_HEADER}

# One command per line
SEGTOOLS_INSTALL_SCRIPT = """
cd $dir
svn co $url
cd $file
python setup.py install
"""

${COMMON_CODE_BODY}

############################## MAIN #########################
def main(args=sys.argv[1:]):
    # Set up shell details
    try:
        shell_name = os.path.basename(os.environ["SHELL"])
    except KeyError:
        shell_name = None
    shell = ShellManager(shell_name)
                
    try:
        # Set up arch_home
        arch_home = setup_arch_home()
        
        # Set up python home
        python_home, default_python_home = setup_python_home(arch_home)
        # Add python_home to PYTHONPATH
        prompt_add_to_env(shell, "PYTHONPATH", python_home)
        
        # Set up bin directory
        script_home, default_script_home = setup_script_home(arch_home)
        # Add script_home to PATH
        prompt_add_to_env(shell, "PATH", script_home)

        # Maybe create pydistutils.cfg
        prompt_create_cfg(arch_home, python_home, default_python_home,
                          script_home, default_script_home)
            
        # Add HDF5, if necessary
        hdf5_dir = prompt_install_hdf5(arch_home)
        if hdf5_dir:
            print >>sys.stderr, ("\nPyTables uses the environment variable"
                                 " HDF5DIR to locate HDF5.")
            prompt_set_env(shell, "HDF5_DIR", hdf5_dir)


        # Add Numpy, if necessary
        prompt_install_numpy()

        # Install segtools (and dependencies)
        prompt_install_segtools(arch_home)

        # Test package installations
        prompt_test_packages(arch_home=arch_home)

        print >>sys.stderr, "\n=========== Installation complete ============="
        
    finally:  # Clean up
        shell.close()
    
########################### GET VERSION ########################
def get_segtools_version():
    """Returns segtools version as a string or None if not found or installed
    
    Temporarily removes '.' from sys.path during installation to prevent
    finding segtools in current directory (but uninstalled)
    """
    dir = os.getcwd()
    index = None
    if dir in sys.path:
        index = sys.path.index(dir)
        del sys.path[index]
        
    try:
        try:
            import segtools
            return segtools.__version__
        except (AttributeError, ImportError):
            return None
    finally:
        if index is not None:
            sys.path.insert(index, dir)

##################### SPECIFIC PROGRAM INSTALLERS ################
def prompt_install_segtools(arch_home):
    return _installer("segtools", install_segtools, get_segtools_version,
                      install_prompt = EASY_INSTALL_PROMPT, arch_home=arch_home)
         
def install_segtools(arch_home, *args, **kwargs):
    segtools_dir = prompt_install_path("segtools", arch_home)
    install_dir = install_script("segtools", segtools_dir,
                                 SEGTOOLS_INSTALL_SCRIPT, url=SEGTOOLS_URL)
    return install_dir

            
if __name__ == "__main__":
    sys.exit(main())
