#! /bin/bash
#
# Copyright (C) 2003-2014 Intel Corporation.  All Rights Reserved.
# 
# The source code contained or described herein and all documents
# related to the source code ("Material") are owned by Intel Corporation
# or its suppliers or licensors.  Title to the Material remains with
# Intel Corporation or its suppliers and licensors.  The Material is
# protected by worldwide copyright and trade secret laws and treaty
# provisions.  No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed, or
# disclosed in any way without Intel's prior express written permission.
# 
# No license under any patent, copyright, trade secret or other
# intellectual property right is granted to or conferred upon you by
# disclosure or delivery of the Materials, either expressly, by
# implication, inducement, estoppel or otherwise.  Any license under
# such intellectual property rights must be express and approved by
# Intel in writing.
#
# (C) 2006 by Argonne National Laboratory.
# 
# 				  MPICH2 COPYRIGHT
# 
# The following is a notice of limited availability of the code, and disclaimer
# which must be included in the prologue of the code and in all source listings
# of the code.
# 
# Copyright Notice
#  + 2002 University of Chicago
# 
# Permission is hereby granted to use, reproduce, prepare derivative works, and
# to redistribute to others.  This software was authored by:
# 
# Mathematics and Computer Science Division
# Argonne National Laboratory, Argonne IL 60439
# 
# (and)
# 
# Department of Computer Science
# University of Illinois at Urbana-Champaign
# 
# 
# 			      GOVERNMENT LICENSE
# 
# Portions of this material resulted from work developed under a U.S.
# Government Contract and are subject to the following license: the Government
# is granted for itself and others acting on its behalf a paid-up, nonexclusive,
# irrevocable worldwide license in this computer software to reproduce, prepare
# derivative works, and perform publicly and display publicly.
# 
# 				  DISCLAIMER
# 
# This computer code material was prepared, in part, as an account of work
# sponsored by an agency of the United States Government.  Neither the United
# States, nor the University of Chicago, nor any of their employees, makes any
# warranty express or implied, or assumes any legal liability or responsibility
# for the accuracy, completeness, or usefulness of any information, apparatus,
# product, or process disclosed, or represents that its use would not infringe
# privately owned rights.
# 
# Portions of this code were written by Microsoft. Those portions are
# Copyright (c) 2007 Microsoft Corporation. Microsoft grants permission to
# use, reproduce, prepare derivative works, and to redistribute to
# others. The code is licensed "as is." The User bears the risk of using
# it. Microsoft gives no express warranties, guarantees or
# conditions. To the extent permitted by law, Microsoft excludes the
# implied warranties of merchantability, fitness for a particular
# purpose and non-infringement.
# 
# 
#
#     
#
# mpif77
# Simple script to compile and/or link MPI programs.
# This script knows the default flags and libraries, and can handle
# alternative C compilers and the associated flags and libraries.
# The important terms are:
#    includedir, libdir - Directories containing an *installed* mpich
#    prefix, execprefix - Often used to define includedir and libdir
#    F77                - Fortran 77 compiler
#    WRAPPER_FFLAGS     - Any special flags needed to compile 
#    WRAPPER_LDFLAGS    - Any special flags needed to link
#    WRAPPER_LIBS       - Any special libraries needed in order to link
#    F77_OTHER_LIBS     - Yet more libraries, needed just with F77
#    
#    
# We assume that (a) the C compiler can both compile and link programs
#
# Handling of command-line options:
#   This is a little tricky because some options may contain blanks.
#
# Special issues with shared libraries - todo
#
# --------------------------------------------------------------------------
# Set the default values of all variables.
#
# Directory locations: Fixed for any MPI implementation.
# Set from the directory arguments to configure (e.g., --prefix=/usr/local)
prefix=I_MPI_SUBSTITUTE_INSTALLDIR
# The environment variable I_MPI_ROOT may be used to override installation folder path  
if [ -n "$I_MPI_ROOT" ] ; then
    prefix=$I_MPI_ROOT;
fi
# Recognize the '-mmic' switch
for arg in "$@" ; do
{
 if [ "${arg}" = "-mmic" ] ; then
  . ${prefix}/mic/bin/mpivars.sh
  if [ -n "$VT_ROOT" ]; then
    if [ -f "$VT_ROOT/mic/bin/itacvars.sh" ]; then
      . "$VT_ROOT/mic/bin/itacvars.sh" ""
    fi
  fi
  exec mpif77 "$@"
 fi
}
done
exec_prefix=${prefix}
sysconfdir=${prefix}/intel64/etc
# The environment variable I_MPI_COMPILER_CONFIG_DIR may be used to override 
# folder where *.conf files are placed  
if [ -n "$I_MPI_COMPILER_CONFIG_DIR" ] ; then
    sysconfdir=$I_MPI_COMPILER_CONFIG_DIR;
fi
includedir=${prefix}/intel64/include
libdir=${prefix}/intel64/lib

# Default settings for compiler, flags, and libraries
# Determined by a combination of environment variables and tests within
# configure (e.g., determining whehter -lsocket is needee)
F77="gfortran"
F77CPP=""
FFLAGS=" "
LDFLAGS=" -ldl "
LIBS="-lrt -lpthread   "
MPIVERSION="5.0 Update 2"
MPILIBNAME="mpi"

enable_wrapper_rpath="yes"

# Internal variables
# Show is set to echo to cause the compilation command to be echoed instead 
# of executed.
Show=
Docompchk=no
static_mpi=no
strip_debug_info=
handle_executable=
executable=a.out
static_log=yes
mt_mpi=no
ilp64=no
trace_opt=no
#
# End of initialization of variables
#---------------------------------------------------------------------
# Environment Variables.
# The environment variables I_MPI_F77, MPICH_F77 may be used to override the 
# default choices. I_MPI_F77 has higher priority than MPICH_F77.
# In addition, if there is a file $sysconfdir/mpif77-$F77name.conf, 
# where F77name is the name of the compiler with all spaces replaced by hyphens
# (e.g., "f77 -64" becomes "f77--64", that file is sources, allowing other
# changes to the compilation environment.  See the variables used by the 
# script (defined above)
if [ -n "$I_MPI_F77" ] ; then
    F77="$I_MPI_F77"
    F77name=`echo $F77 | sed 's/ /-/g'`
    if [ -s $sysconfdir/mpif77-$(basename $F77name).conf ] ; then
        . $sysconfdir/mpif77-$(basename $F77name).conf
    fi
else
    if [ -n "$MPICH_F77" ] ; then
        F77="$MPICH_F77"
        F77name=`echo $F77 | sed 's/ /-/g'`
        if [ -s $sysconfdir/mpif77-$(basename $F77name).conf ] ; then
            . $sysconfdir/mpif77-$(basename $F77name).conf
        fi
    fi
fi
if [ -n "$I_MPI_CHECK_COMPILER" ] ; then
    for comp_val in "1" "on" "yes" "enable"
    do
        if [ "$I_MPI_CHECK_COMPILER" = "$comp_val" ] ; then
            Docompchk=yes
            break
        fi
    done
fi
if [ -n "$I_MPI_DEBUG_INFO_STRIP" ] ; then
    for comp_val in "0" "off" "no" "disable"
    do
        if [ "$I_MPI_DEBUG_INFO_STRIP" = "$comp_val" ] ; then
            strip_debug_info=no
            break
        fi
    done
fi
# Allow a profiling option to be selected through an environment variable
if [ -n "$MPIF77_PROFILE" ] ; then
    profConf=$MPIF77_PROFILE
fi
if [ -n "$I_MPI_F77_PROFILE" ] ; then
    profConf=$I_MPI_F77_PROFILE
fi
if [ -n "$MPIFC_PROFILE" ] ; then
    profConf=$MPIFC_PROFILE
fi
if [ -n "$I_MPI_FC_PROFILE" ] ; then
    profConf=$I_MPI_FC_PROFILE
fi

# Override default mpi library
if [ -n "$I_MPI_LINK" ] ; then
    mpilib_override=$I_MPI_LINK
fi

#
# ------------------------------------------------------------------------
# Argument processing.
# This is somewhat awkward because of the handling of arguments within
# the shell.  We want to handle arguments that include spaces without 
# loosing the spacing (an alternative would be to use a more powerful
# scripting language that would allow us to retain the array of values, 
# which the basic (rather than enhanced) Bourne shell does not.  
#
# Look through the arguments for arguments that indicate compile only.
# If these are *not* found, add the library options

linking=yes
allargs=("$@")
argno=0
cppflags=()
for arg in "$@" ; do
    # Set addarg to no if this arg should be ignored by the C compiler
    addarg=yes
    if [ "x$handle_executable" = "xyes" ] ; then
	executable=$arg
	handle_executable=
    fi
    case "$arg" in 
 	# ----------------------------------------------------------------
	# Compiler options that affect whether we are linking or no
    -c|-S|-E|-M|-MM)
    # The compiler links by default
    linking=no
    ;;
    -o )
    handle_executable=yes
    addarg=yes
    ;;
	# ----------------------------------------------------------------
	# Options that control how we use mpif77 (e.g., -show, 
	# -f77=* -config=*
    -echo)
    addarg=no
    set -x
    ;;

    -f77=*)
    F77=`echo A$arg | sed -e 's/A-f77=//g'`
    addarg=no
    ;;
    -fc=*)
    F77=`echo A$arg | sed -e 's/A-fc=//g'`
    addarg=no
    ;;

    -show)
    addarg=no
    Show=echo
    ;;
    -config=*)
    addarg=no
    F77name=`echo A$arg | sed -e 's/A-config=//g'`
    if [ -s "$sysconfdir/mpif77-$F77name.conf" ] ; then
        . "$sysconfdir/mpif77-$F77name.conf"
    else
	echo "Configuration file mpif77-$F77name.conf not found"
    fi
    ;;
    -compile-info|-compile_info)
    # -compile_info included for backward compatibility
    Show=echo
    addarg=no
    ;;
    -link-info|-link_info)
    # -link_info included for backward compatibility
    Show=echo
    addarg=no
    ;;
    -v)
    # Pass this argument to the compiler as well.
    echo "$(basename $0) for the Intel(R) MPI Library $MPIVERSION for Linux*"
    echo "Copyright(C) 2003-2014, Intel Corporation.  All rights reserved."
    # if there is only 1 argument, it must be -v.
    if [ "$#" -eq "1" ] ; then
        linking=no
    fi
    ;;
    -profile=*)
    # Pass the name of a profiling configuration.  As
    # a special case, lib<name>.so or lib<name>.la may be used
    # if the library is in $libdir
    profConf=`echo A$arg | sed -e 's/A-profile=//g'`
    addarg=no
    # Loading the profConf file is handled below
    ;;
    -help)
    # Print mini-help if started without parameters
    echo "Simple script to compile and/or link MPI programs."
    echo "Usage: `basename $0` [options] <files>"
    echo "----------------------------------------------------------------------------" 
    echo "The following options are supported:"
    echo "   -fc=<name> | -f77=<name>"
    echo "                   specify a FORTRAN compiler name: i.e. -fc=g77"
    echo "   -echo           print the scripts during their execution"
    echo "   -show           show command lines without real calling"
    echo "   -config=<name>  specify a configuration file: i.e. -config=g77 for mpif77-g77.conf file" 
#    echo "   -compile-info   show compiler command line"
#    echo "   -link-info      show linker command line"
    echo "   -v              print version info of $(basename $0) and its native compiler"
    echo "   -profile=<name> specify a profile configuration file (an MPI profiling"
    echo "                   library): i.e. -profile=myprofile for the myprofile.cfg file."
    echo "                   As a special case, lib<name>.so or lib<name>.a may be used"
    echo "                   if the library is found"
    echo "   -check_mpi      link against the Intel(R) Trace Collector (-profile=vtmc)."
#    echo "   -compchk        enable compiler setup checks"
    echo "   -static_mpi     link the Intel(R) MPI Library statically"
    echo "   -mt_mpi         link the thread safe version of the Intel(R) MPI Library"
    echo "   -ilp64          link the ILP64 support of the Intel(R) MPI Library"
    echo "   -t or -trace"
    echo "                   link against the Intel(R) Trace Collector"
    echo "   -dynamic_log    link against the Intel(R) Trace Collector dynamically"
    echo "   -static         use static linkage method"
    echo "   -nostrip        turn off the debug information stripping during static linking"
    echo "   -O              enable optimization"
    echo "   -link_mpi=<name>"
    echo "                   link against the specified version of the Intel(R) MPI Library"
    echo "All other options will be passed to the compiler without changing."
    echo "----------------------------------------------------------------------------" 
    echo "The following environment variables are used:"
    echo "   I_MPI_ROOT      the Intel(R) MPI Library installation directory path" 
    echo "   I_MPI_F77 or MPICH_F77"  
    echo "                   the path/name of the underlying compiler to be used"
    echo "   I_MPI_FC_PROFILE or I_MPI_F77_PROFILE or MPIF77_PROFILE" 
    echo "                   the name of profile file (without extension)" 
    echo "   I_MPI_COMPILER_CONFIG_DIR" 
    echo "                   the folder which contains configuration files *.conf"
    echo "   I_MPI_TRACE_PROFILE"
    echo "                   specify a default profile for the -trace option"
    echo "   I_MPI_CHECK_PROFILE"
    echo "                   specify a default profile for the -check_mpi option"
    echo "   I_MPI_CHECK_COMPILER"
    echo "                   enable compiler setup checks"
    echo "   I_MPI_LINK      specify the version of the Intel(R) MPI Library"
    echo "   I_MPI_DEBUG_INFO_STRIP"
    echo "                   turn on/off the debug information stripping during static linking"
    echo "----------------------------------------------------------------------------" 
    exit 0
    ;;
    -nolinkage)
    # This internal option is used by wrapper driver scripts mpicc, mpicxx, mpifc when -v option is used.
    linking=no
    addarg=no
    ;;
    -g)
    MPILIBDIR="/debug"
    ;;
    -compchk)
    Docompchk=yes
    addarg=no
    ;;
    -nocompchk) # Tr#2500
    addarg=no   # Ignore this option
    ;;
    -static_mpi)
    static_mpi=yes
    FFLAGS="$FFLAGS -Xlinker --export-dynamic"
    addarg=no
    ;;
    -static_log)
    static_log=yes
    addarg=no
    ;;
    -dynamic_log)
    static_log=no
    addarg=no
    ;;
    -static)
    static_mpi=yes
    static_log=yes
    FFLAGS="$FFLAGS -Xlinker --export-dynamic"
    addarg=yes
    ;;
    -mt_mpi)
    mt_mpi=yes
    addarg=no
    ;;
    -ilp64)
    ilp64=yes
    addarg=no
    ;;
    -i8)
    ilp64=yes
    if [ "$F77" = gfortran ]; then FFLAGS="-fdefault-integer-8 $FFLAGS"; fi
    addarg=no
    ;;
    -check_mpi)
    if [ -z "$profConf" ]; then
        if [ -z "$I_MPI_CHECK_PROFILE" ]; then  
            profConf="vtmc"  
        else  
            profConf="$I_MPI_CHECK_PROFILE"  
        fi
    else
        echo "Warning: the -check_mpi option will be ignored because the profile was set."
    fi  
    addarg=no  
    ;;  
    -t | -trace | -t=* | -trace=* )  
    if [ -z "$profConf" ]; then
        if [ -z "$I_MPI_TRACE_PROFILE" ]; then  
            profConf="vt"  
        else  
            profConf="$I_MPI_TRACE_PROFILE"  
        fi  
    else
        echo "Warning: the -trace option will be ignored because the profile was set."
    fi  
    addarg=no
    ;;
    -nativelinking)
    # Internal option to use native compiler for linking without MPI libraries
    nativelinking=yes
    addarg=no
    ;;
    -fopenmp )
    mt_mpi=yes
    ;;
    -link_mpi=* )
    mpilib_override=`echo A$arg | sed -e 's/A-link_mpi=//g'`
    addarg=no
    ;;
    -mmic )
    addarg=no
    ;;
    -nostrip )
    strip_debug_info=no
    addarg=no
    ;;
        # -----------------------------------------------------------------
	# Other arguments.  We are careful to handle arguments with 
	# quotes (we try to quote all arguments in case they include 
	# any spaces)
    *\"*) 
    qarg="'"$arg"'"
    case $arg in 
       -D*)
       cppflags="$cppflags $qarg"
       ;;
    esac
    ;;
    *\'*) 
    qarg='\"'"$arg"'\"'
    case $arg in 
       -D*)
       cppflags="$cppflags $qarg"
       ;;
    esac
    ;;

    # The following are special args used to handle .F files when the
    # Fortran compiler itself does not handle these options
    -I*)
    cppflags[${#cppflags}]="$arg"
    ;;
    -D*)
    cppflags[${#cppflags}]="$arg"
    ;;
    *.F|*.F90|*.fpp|*.FPP)
# If F77CPP is not empty, then we need to do the following:
#    If any input files have the .F or .F90 extension, then    
#        If F77CPP = false, then
#            generate an error message and exit
#        Use F77CPP to convert the file from .F to .f, using 
#            $TMPDIR/f$$-$count.f as the output file name
#            Replace the input file with this name in the args
# This is needed only for very broken systems
#     
    if [ -n "$F77CPP" ] ; then
        if [ "$F77CPP" = "false" ] ; then
            echo "This Fortran compiler does not accept .F or .F90 files"
	    exit 1
        fi
        addarg=no
	# Remove and directory names and extension
	$ext=`expr "$arg" : '.*\(\..*\)'`
        bfile=`basename $arg $ext`
	# 
	TMPDIR=${TMPDIR:-/tmp}
        tmpfile=$TMPDIR/f$$-$bfile.f
        if $F77CPP "${cppflags[@]}" $arg > $tmpfile ; then
            # Add this file to the commandline list
	    count=`expr $count + 1`
	    allargs[${#allargs}]="$tmpfile"
	    rmfiles="$rmfiles $tmpfile"
        else
	    echo "Aborting compilation because of failure in preprocessing step"
	    echo "for file $arg ."
	    exit 1
        fi
    fi
    # Otherwise, just accept the argument
    ;;
    # - end of special handling for .F files
    
    esac
    if [ $addarg = no ] ; then
        unset allargs[$argno]
    fi
    # Some versions of bash do not accept ((argno++))
    argno=`expr $argno + 1`
done

if [ $# -eq 0 ] ; then
    echo "Error: Command line argument is needed!"
    "$0" -help
    exit 1
fi

MPILIBDIR_MT="mt"
if [ -n "$mpilib_override" ] ; then
    case "$mpilib_override" in
       opt )
           mt_mpi=no
           MPILIBDIR="/release"
           MPILIBNAME="mpi"
           MPILIBDIR_MT=
           ;;
       opt_mt )
           mt_mpi=yes
           MPILIBDIR="/release"
           ;;
       dbg )
           mt_mpi=no
           MPILIBDIR="/debug"
           MPILIBDIR_MT=
           ;;
       dbg_mt )
           mt_mpi=yes
           MPILIBDIR="/debug"
           ;;
       * )
           echo "Warning: incorrect library version specified. Automatically selected library will be used."
           ;;
    esac
fi

# -----------------------------------------------------------------------
case "$MPILIBDIR" in
    release | /release | debug | /debug | log | /log )
	if [ ! -z "$MPILIBDIR_MT" ]; then
	    MPILIBDIR=${MPILIBDIR}_${MPILIBDIR_MT}
	fi
	;;
    "" )
	MPILIBDIR=/release_mt
	;;
esac
if [ "$static_mpi" = yes ] ; then
    mpilibs="${libdir}/libmpifort.a ${libdir}${MPILIBDIR}/lib${MPILIBNAME}.a"
    I_MPI_OTHERLIBS=" $libdir/libmpigi.a"
    if [ "$ilp64" = yes ]; then
	mpilibs="$libdir/libmpi_ilp64.a $mpilibs"
    fi
    if [ "x$strip_debug_info" = "x" ] ; then
	strip_debug_info=yes
    fi
else
    mpilibs="-lmpifort -l$MPILIBNAME"
    I_MPI_OTHERLIBS=" -lmpigi"
    if [ "$ilp64" = yes ]; then
	mpilibs="-lmpi_ilp64 $mpilibs"
    fi
fi
# Derived variables.  These are assembled from variables set from the
# default, environment, configuration file (if any) and command-line
# options (if any)
f77libs=
if [ "mpifort" != "mpi" ] ; then
    f77libs="-lmpifort"
fi

PROFILE_FOO=
# Handle the case of a profile switch
if [ -n "$profConf" ] ; then
    profConffile=
    if [ -s "$libdir/lib$profConf.a" -o -s "$libdir/lib$profConf.so" ] ; then
	PROFILE_FOO="-l$profConf"
        mpilibs="-l$profConf $mpilibs"
    elif [ -s "$sysconfdir/$profConf.conf" ] ; then
	profConffile="$sysconfdir/$profConf.conf"
    elif [ -s "$profConf.conf" ] ; then
        profConffile="$profConf.conf"
    else
        echo "Profiling configuration file $profConf.conf not found in $sysconfdir"
    fi
    if [ -n "$profConffile" -a -s "$profConffile" ] ; then
	. $profConffile
        if [ -n "$PROFILE_INCPATHS" ] ; then                                                                            
           CFLAGS="$PROFILE_INCPATHS $CFLAGS"                                                                          
        fi                                                                                                             
        if [ -n "$PROFILE_PRELIB" ] ; then                                                                             
           mpilibs="$PROFILE_PRELIB $mpilibs"                                                                          
        fi
        if [ -n "$PROFILE_POSTLIB" ] ; then
           mpilibs="$mpilibs $PROFILE_POSTLIB"
        fi
    fi
fi

# A temporary statement to invoke the compiler
# Place the -L before any args incase there are any mpi libraries in there.
# Eventually, we'll want to move this after any non-MPI implementation 
# libraries
#
if [ "$Docompchk" = "yes" ]; then
    $Show $prefix/intel64/bin/compchk.sh "32e" "$0"
    rc=$?
    if [ $rc -ne 0 ]; then
	exit $rc
    fi
fi
rpath_opt="-Xlinker --enable-new-dtags -Xlinker -rpath -Xlinker ${libdir}${MPILIBDIR} -Xlinker -rpath -Xlinker $libdir -Xlinker -rpath -Xlinker /opt/intel/mpi-rt/5.0/mic/lib${MPILIBDIR} -Xlinker -rpath -Xlinker /opt/intel/mpi-rt/5.0/mic/lib"
rpath_opt="-Xlinker --enable-new-dtags -Xlinker -rpath -Xlinker ${libdir}${MPILIBDIR} -Xlinker -rpath -Xlinker $libdir -Xlinker -rpath -Xlinker /opt/intel/mpi-rt/5.0/intel64/lib${MPILIBDIR} -Xlinker -rpath -Xlinker /opt/intel/mpi-rt/5.0/intel64/lib"
if [ "$linking" = yes ] ; then
    # Attempt to encode rpath info into the executable if the user has not
    # disabled rpath usage and some flavor of rpath makes sense on this
    # platform.
    # TODO configure and config.rpath are computing more sophisticated rpath
    # schemes than this simple one.  Consider updating this logic accordingly.
    if test "X$enable_wrapper_rpath" = "Xyes" ; then
        eval rpath_flags=\"${hardcode_libdir_flag_spec}\"
    else
	rpath_flags=""
    fi

    if [ "$nativelinking" = yes ] ; then
        $Show $F77 $PROFILE_INCPATHS    -ldl  "${allargs[@]}" -I$includedir
        rc=$?
    else
        $Show $F77 $FFLAGS "${allargs[@]}" -I$includedir ${path_list} -L${libdir}${MPILIBDIR} -L${libdir} $rpath_opt $mpilibs $I_MPI_OTHERLIBS $LDFLAGS $LIBS
	rc=$?
        if [ $rc -eq 0 -a "x$strip_debug_info" = "xyes" ] ; then
	    $Show objcopy --only-keep-debug ${executable} ${executable}.dbg
	    $Show objcopy --strip-debug ${executable}
	    $Show objcopy --add-gnu-debuglink=${executable}.dbg ${executable}
	fi
    fi
else
    $Show $F77 $PROFILE_INCPATHS   "${allargs[@]}" -I$includedir
    rc=$?
fi
if [ -n "$rmfiles" ] ; then
    for file in $rmfiles ; do
        objfile=`basename $file .f`
	if [ -s "${objfile}.o" ] ; then
	    # Rename 
	    destfile=`echo $objfile | sed -e "s/.*$$-//"`
	    mv -f ${objfile}.o ${destfile}.o
	fi
        rm -f $file
    done
    rm -f $rmfiles
fi
exit $rc

