#  Copyright (C) 2008 The University of British Columbia
#  
#  This program 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 2 of the License, or
#  (at your option) any later version.
#  
#  This program 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 this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from slabcore import *
from os.path import join
from glob import glob
from sys import stdout
import os

env = Environment( )

LoadConfigFile( env )


#===============================================================================
# Variables
#===============================================================================
vars = Variables( )

mpicc_var = PackageVariable('MPICC', 'mpi c compiler', env.get('MPICC',True) )
mpicxx_var = PackageVariable('MPICXX', 'mpi c++ compiler', env.get('MPICXX',True) )
mpicpppath_var = PackageVariable('MPICPPPATH', 'mpi include paths', env.get('MPICPPPATH',[]) )
mpilibpath_var = PackageVariable('MPILIBPATH', 'mpi library paths', env.get('MPILIBPATH',[]) )

vars.Add( mpicc_var )
vars.Add( mpicxx_var )
vars.Add( mpicpppath_var )
vars.Add( mpilibpath_var )
vars.Update( env )

#===============================================================================
# HELP
#===============================================================================
Help( "\n" )
Help( "\n" )
Help( "Options for 'math' external tool:" )
Help( vars.GenerateHelpText(env) )

#===============================================================================
# Configuration
#===============================================================================
ctool = ToolCreator( 'cmpi' )
cpptool = ToolCreator( 'cxxmpi' )

mpictext = """

#include <mpi.h>
int main( int c, char**v )
{
    MPI_Init( &c, &v );
    MPI_Finalize();
    return 1;   
}

"""

def CheckCMPI( context ):
    
    context.Message( "checking mpicc ... "); stdout.flush()
    if context.TryLink( mpictext ,".c"):
        context.Result(True)
        return True
    else:
        context.Result(False)
        return False
        

def CheckCXXMPI( context ):
    
    context.Message( "checking mpicxx ... "); stdout.flush()
    if context.TryLink( mpictext ,".cpp"):
        context.Result(True)
        return True
    else:
        context.Result(False)
        return False
        
    return 

if DoConfig( env ):
    conf  = Configure(env,conf_dir="#/config-etc/tests",log_file="#/config-etc/config.log",
                      custom_tests = { 'CheckCMPI' : CheckCMPI,
                                      'CheckCXXMPI':CheckCXXMPI } )
    
    MPICPPPATH =env.get('MPICPPPATH')
    MPILIBPATH =env.get('MPILIBPATH')
    if MPICPPPATH:
        ctool.Append( CPPPATH=MPICPPPATH )
        cpptool.Append( CPPPATH=MPICPPPATH )
        conf.env.Append( CPPPATH=MPICPPPATH )
        
    if MPILIBPATH:
        ctool.Append( LIBPATH=MPILIBPATH )
        cpptool.Append( LIBPATH=MPILIBPATH )
        conf.env.Append( LIBPATH=MPILIBPATH )
        
    # MPI CC config
    MPICC = env.get('MPICC')
    
    if MPICC is True:
        MPICC = env.WhereIs( 'mpicc' )
        if not MPICC:
            MPICC = env.WhereIs( 'mpicc' , os.environ['PATH'] )
            
    if MPICC:
        ctool.Replace( CC=MPICC )
        env.Replace( CC=MPICC )
        
        if conf.CheckCMPI( ):
#        if conf.CheckCHeader( "mpi.h", "<>" ):
            ctool.Exists(True)
        else:
            ctool.Exists(False)
    else:
        ctool.Exists(False)

    # MPI CXX config
    MPICXX = env.get('MPICXX')
    
    if MPICXX is True:
        MPICXX = env.WhereIs( 'mpicxx' )
        if not MPICXX:
            MPICXX = env.WhereIs( 'mpicxx' , os.environ['PATH'] )
            
    if MPICXX:
        cpptool.Replace( CXX=MPICXX )
        env.Replace( CXX=MPICXX )
        
        if conf.CheckCXXMPI( ):
#        if conf.CheckCHeader( "mpi.h", "<>" ):
            cpptool.Exists(True)
        else:
            cpptool.Exists(False)
    else:
        cpptool.Exists(False)
            
    
#    if env.get('MATH'):
#        MATH        = env.get('MATH')
#        mathpath    = None
#        mathlibpath = None
#        if isinstance( MATH , str):
#            # Header path
#            mathpath = join( MATH, 'include' )
#            conf.env['CPPPATH'] = mathpath
#            # Library path
#            mathlibpath = join( MATH, 'lib' )
#            conf.env['LIBPATH'] = mathlibpath
#    
#        if conf.CheckLibWithHeader( ['m'],['math.h','complex.h'], 'c', autoadd=False):
#            tc.Prepend( LIBS=['m'] )
#            if mathpath:
#                tc.Prepend( CPPPATH=mathpath )
#            if mathlibpath:
#                tc.Prepend( LIBPATH=mathlibpath )
#            tc.Exists(True)
#        else:
#            tc.Exists(False)
        
    env = conf.Finish( )
    
#===============================================================================
# Write file
#===============================================================================
ctool.CreateTool(env)
cpptool.CreateTool(env)

