#!/bin/sh

# General settings
PROJECT="KOJAK/Scalasca"
LOG_ANNEX="/tmp/scalasca-config-annex.$$.log"
LOGFILE="/tmp/scalasca-config-$$.log"


####################
# Helper functions #
####################

usage () {
  cat > /dev/tty <<[[EOT]]
usage  : $0 [options]
options: [--prefix=DIR]                # Installation directory
         [--disable-mpi-wrappers=[<group>[,<group>[,...]]] # do not wrap
                                       # certain groups of MPI calls
                                       # <group> := (CG|COLL|ENV|ERR|EXT|EXTRA|
                                       #             IO|MINI|MISC|P2P|RMA|SPAWN|
                                       #             TOPO|TYPE)
         [--enable-all-mpi-wrappers]   # enable all available MPI wrappers
         [--with-binutils=DIR]         # Binutils installation directory
         [--with-papi=DIR]             # PAPI installation directory
         [--with-vtf3=DIR]             # VTF3 installation directory
         [--with-opari2=DIR]           # OPARI2 installation directory
         [--with-otf=DIR]              # OTF installation directory
         [--with-pdt=DIR]              # PDToolkit installation directory
         [--with-qmake=PATH]           # Qt's qmake (name or absolute path)
         [--with-sionconfig=PATH]      # SIONlib's sionconfig (name or absolute path)
         [--with-paraver-cfg=FILE]     # Paraver Integration config file FILE
         [--force-(basic|32|64|32-64|cross)]  # Force basic, 32-bit, 64-bit,
                                       # 32-bit and 64-bit, or cross-compiling
                                       # installation
         [--disable-(mpi|omp|ompi)]    # Disable MPI, OpenMP, or hybrid
                                       # MPI/OpenMP measurement support
         [--disable-fortran]           # Disable Fortran measurement support
         [--disable-gui]               # Disable CUBE viewer build
         [--disable-zlib]              # Disable trace compression

additional options [ONLY TO BE USED IF DIRECTED BY configure]:
         [--compiler=(gnu|pgi|intel|path|ibm|sun|clang)] # Compiler selection
                                                         # (Linux only)
         [--mpi=(mpich|mpich2|lam|openmpi|intel|         # MPI-Lib selection
                 intel2|hp|scali|mpibull2|bullxmpi|      # (Linux/Solaris only)
                 sun|ibmpoe|intelpoe)]
[[EOT]]
}

CFGecho () {
  echo "$1" | tee -a ${LOGFILE}
}

ErrorAndExit () {
  echo "ERROR: $1"
  exit 1
}

ConfigGNUmake () {
  echo ""
  echo "#------------------------------------------------------------------------------"
  echo "# GNU Make Support"
  echo "#-----------------------------------------------------------------------------"
  echo ""
  echo "MAKE = ${MK}"

}

ForceAbsolutePath () {
  case "$2" in
    /* )
      ;;
    *)
      ErrorAndExit "Expected an absolute path for $1"
      ;;
  esac
}

CheckExecutable () {
  if [ ! -f $2 -o ! -x $2 ]
  then
    ErrorAndExit "--with-$1: $2 not a regular executable file."
  fi
}

CheckWithDirectoryParameter () {
  if [ ! -d $2 ]
  then
    ErrorAndExit "--with-$1: Directory $2 not found."
  elif [ ! -r $2/$3 ]
  then
    ErrorAndExit "--with-$1: $2/$3 not found."
  fi
  ForceAbsolutePath "--with-$1" $2
}

ExtractSuffix () {
  case $1 in
    B:*) VAR=`echo $1 | sed -e 's/^B://'`
         SSUF=".be";;
    F:*) VAR=`echo $1 | sed -e 's/^F://'`
         SSUF=".fe";;
    *:*) echo "Warning: Ignoring variable with unknown qualifier ${VAR}"
         SSUF="";;
      *) SSUF="";;
  esac
}

########################
# Command line parsing #
########################

PREFIX="/opt/scalasca"
COMP=""
HASXLCOMP=""
GFORTRAN=""
BINUTILSDIR=""
PAPIDIR=""
VTF3DIR=""
OPARI2DIR=""
OTFDIR=""
PDTDIR=""
SLOG2DIR=""
SZLIB=""
SIONLIB=""
MPI=""
HYBRID="yes"
DISABLE=""
FORCE=""
PREC=""
DEFPREC=""
LIBS=""
QMAKE=""
TAUARCH32=NA
TAUARCH64=NA
EXCL_MPI_DEFS="-DNO_MPI_EXTRA"
NOGUI=""
NOFOR=""
MPINM="nm"
NONSTDMPIO=""
NONSTDMPIEXT=""
ALLOWCOMP=""
ALLOWMPI=""
CFGSEDSCRIPT=/tmp/config-$$.sed
PRVCFG=""
ISKCOMPUTER=""
ISMIC=""

for arg in "$@"
do
  case ${arg} in
  --help|-help|-h)
          usage
          exit 1
          ;;
  --prefix=*)
          PREFIX=`echo $arg | sed -e 's/--prefix=//'`
          PREFIX=`eval echo ${PREFIX}`    # tilde and variable expansion
          ForceAbsolutePath "--prefix" "${PREFIX}"
          ;;
  --with-binutils=*)
          BINUTILSDIR=`echo $arg | sed -e 's/--with-binutils=//'`
          BINUTILSDIR=`eval echo ${BINUTILSDIR}`    # tilde and variable expansion
          CheckWithDirectoryParameter binutils ${BINUTILSDIR} include/bfd.h
          ;;
  --with-papi=*)
          PAPIDIR=`echo $arg | sed -e 's/--with-papi=//'`
          if [ -d /opt/cray/xt-asyncpe ]        # CrayXT needs module to be loaded
          then
              if [ -z "${PAPI_INCLUDE_OPTS}" ]; then
                  echo "PAPI_INCLUDE_OPTS not defined; ensure xt-papi or papi module is loaded"
                  exit
              fi
          else
              PAPIDIR=`eval echo ${PAPIDIR}`    # tilde and variable expansion
              CheckWithDirectoryParameter papi ${PAPIDIR} include/papi.h
              LIBS="${LIBS} PAPI"
          fi
          ;;
  --with-vtf3=*)
          VTF3DIR=`echo $arg | sed -e 's/--with-vtf3=//'`
          VTF3DIR=`eval echo ${VTF3DIR}`    # tilde and variable expansion
          CheckWithDirectoryParameter vtf3 ${VTF3DIR} include/vtf3.h
          LIBS="${LIBS} VTF3"
          ;;
  --with-opari2=*)
          OPARI2DIR=`echo $arg | sed -e 's/--with-opari2=//'`
          OPARI2DIR=`eval echo ${OPARI2DIR}`    # tilde and variable expansion
          CheckWithDirectoryParameter opari2 ${OPARI2DIR} bin/opari2
          CheckWithDirectoryParameter opari2 ${OPARI2DIR} bin/opari2-config
          ForceAbsolutePath "---with-opari2" "${OPARI2DIR}"
          ;;
  --with-otf=*)
          OTFDIR=`echo $arg | sed -e 's/--with-otf=//'`
          OTFDIR=`eval echo ${OTFDIR}`    # tilde and variable expansion
          CheckWithDirectoryParameter otf ${OTFDIR} include/otf.h
          LIBS="${LIBS} OTF"
          ;;
  --with-pdt=*)
          PDTDIR=`echo $arg | sed -e 's/--with-pdt=//'`
          PDTDIR=`eval echo ${PDTDIR}`    # tilde and variable expansion
          CheckWithDirectoryParameter pdt ${PDTDIR} include/pdb.h
          ForceAbsolutePath "--with-pdt" "${PDTDIR}"
          ;;
  --with-slog2=*)
          SLOG2DIR=`echo $arg | sed -e 's/--with-slog2=//'`
          SLOG2DIR=`eval echo ${SLOG2DIR}`    # tilde and variable expansion
          CheckWithDirectoryParameter slog2 ${SLOG2DIR} src/logformat/trace/trace_API.h
          ;;
  --with-qmake=*)
          QMAKE=`echo $arg | sed -e 's/--with-qmake=//'`
          QMAKE=`eval echo ${QMAKE}`    # tilde and variable expansion
          ForceAbsolutePath "--with-qmake" "${QMAKE}"
          CheckExecutable qmake "${QMAKE}"
          ;;
  --with-paraver-cfg=*)
          PRVCFG=`echo $arg | sed -e 's/--with-paraver-cfg=//'`
          PRVCFG=`eval echo ${PRVCFG}`  # tilde and variable expansion
          ForceAbsolutePath "--with-paraver-cfg" "${PRVCFG}"
          ;;
  --compiler=*)
          COMP=`echo $arg | sed -e 's/--compiler=//'`
          ;;
  --mpi=*)
          MPI=`echo $arg | sed -e 's/--mpi=//'`
          ;;
  --disable-mpi-wrappers=*)
          EXCL_MPI_WRAP=`echo $arg | sed -e 's/--disable-mpi-wrappers=//' -e 's/[:,]/ /g' | tr "[a-z]" "[A-Z"`
          for group in ${EXCL_MPI_WRAP}
          do
            EXCL_MPI_DEFS="${EXCL_MPI_DEFS} -DNO_MPI_$group"
          done
          ;;
  --enable-all-mpi-wrappers)
          # disable any 'NO_MPI_...' defines
          EXCL_MPI_DEFS=""
          ;;
  --with-sionconfig=*)
          SIONLIBCONFIG=`echo $arg | sed -e 's/--with-sionconfig=//'`
          SIONLIBCONFIG=`eval echo ${SIONLIBCONFIG}`    # tilde and variable expansion
          ForceAbsolutePath "--with-sionconfig" "${SIONLIBCONFIG}"
          CheckExecutable sionconfig "${SIONLIBCONFIG}"
          # SIONlib >= v1.3p5 is required
          SIONVER="unknown"
          if [ -r ${SIONLIBCONFIG} ]; then
            SIONVER=`${SIONLIBCONFIG} --version 2>&1 | cut -d ' ' -f 3 | sed -e 's/.$//'`
          fi
          if [ $SIONVER = "unknown" ]; then
            ErrorAndExit "--with-sionconfig: No suitable SIONlib found: need version >= 1.3p5"
          fi
          SIONLIB="sion"
          LIBS="${LIBS} SION"
          ;;
  --disable-fortran)
          NOFOR="yes"
          ;;
  --disable-gui)
          NOGUI="yes"
          ;;
  --disable-zlib)
          SZLIB="no"
          ;;
  --disable-*)
          NO=`echo $arg | sed -e 's/--disable-//'`
          case ${NO} in
            mpi) if [ "${DISABLE}" = "omp" -o "${DISABLE}" = "ompi" ]
                 then
                   DISABLE=ompi
                 else
                   DISABLE=mpi
                 fi
                 ;;
            omp|openmp) if [ "${DISABLE}" = "mpi" -o "${DISABLE}" = "ompi" ]
                 then
                   DISABLE=ompi
                 else
                   DISABLE=omp
                 fi
                 ;;
            ompi) DISABLE=ompi
                 ;;
            *)   ErrorAndExit "--disable: Unknown feature '${NO}'"
                 ;;
          esac
          ;;
  --force-*)
          FRC=`echo $arg | sed -e 's/--force-//'`
          case ${FRC} in
            basic|32-64|cross) FORCE=${FRC}
                 ;;
            32|64) FORCE=basic
                 PREC=${FRC}
                 ;;
            *)   ErrorAndExit "--force: Unknown feature '${FRC}'"
                 ;;
          esac
          ;;
  *)      # -- Check for VAR=VALUE Makefile.def change requests
          if echo ${arg} | grep -q '^[A-Z][A-Z0-9_:]*=.*$'
          then
            # [B:|F:] VARIABLE = VALUE
            VAR=`echo ${arg} | sed -e 's/\(^[A-Z][A-Z0-9_:]*\)=.*$/\1/'`
            VAL=`echo ${arg} | sed -e 's/^[A-Z][A-Z0-9_:]*=\(.*$\)/\1/'`
            ExtractSuffix ${VAR}
            echo "s|^#*${VAR}.*$|${VAR} = ${VAL}|" >> ${CFGSEDSCRIPT}${SSUF}
          elif echo ${arg} | grep -q '^[A-Z][A-Z0-9_:]*+=.*$'
          then
            # [B:|F:] VARIABLE += VALUE
            VAR=`echo ${arg} | sed -e 's/\(^[A-Z][A-Z0-9_:]*\)+=.*$/\1/'`
            VAL=`echo ${arg} | sed -e 's/^[A-Z][A-Z0-9_:]*+=\(.*$\)/\1/'`
            ExtractSuffix ${VAR}
            echo "s|^#*\(${VAR}.*\)$|\1 ${VAL}|" >> ${CFGSEDSCRIPT}${SSUF}
          else
            ErrorAndExit "unknown option '${arg}'"
          fi
          ;;
  esac
done

if [ -z "${OPARI2DIR}" ]
then
  OPARI2DIR=${PREFIX}
  if [ ! -f opari2/COPYING ]
  then
    ErrorAndExit "Missing --with-opari2=DIR option."
  fi
fi

# Installation prefix checks
if [ -d ${PREFIX} ]
then
  if [ -w ${PREFIX} ]
  then
    CFGecho "WARNING: Installation directory ${PREFIX} exists."
    CFGecho "         Existing content will be overwritten when installing."
    CFGecho ""
  else
    CFGecho "WARNING: Installation directory ${PREFIX} not writable."
    CFGecho ""
  fi
elif touch ${PREFIX} 2> /dev/null
then
  rm ${PREFIX}
else
  CFGecho "WARNING: Installation directory ${PREFIX} not writable."
  CFGecho ""
fi

########################
# Platform recognition #
# -> determine MD + MF #
########################

SYSTEM=`uname -s`
MD=""
MDF=""
MDB=""
MF=Makefile.basic
SWCLOCK=""
MMTIMER=""

case ${SYSTEM} in
  Linux) MK=make
         ;;
  *)     . ./utils/build/select-gmake.sh
         ;;
esac

case ${SYSTEM} in
  Linux) CPU=`uname -m`
         if [ ${CPU} = "ia64" -a -f /etc/sgi-release ]
         then
           CFGMSG="SGI Altix with Intel compilers"
           MD=Makefile.defs.sgi-intel
           if [ -z "${BINUTILSDIR}" -a ! -f /usr/include/bfd.h ]
           then
                ErrorAndExit "BFD required; specify --with-binutils"
           fi
           if [ -e /usr/include/sn/mmtimer.h ]
           then
             MMTIMER=yes
           fi
           NONSTDMPIEXT="yes"
           EXCL_MPI_DEFS="${EXCL_MPI_DEFS} -DNO_MPI_EXT"
         elif [ ${CPU} = "x86_64" -a -f /opt/pce/bin/xd1launcher ]
         then
           CFGMSG="Cray XD1 with PGI compilers"
           MD=Makefile.defs.linux-pgi
         elif [ ${CPU} = "ppc64" -a -d /bgl/BlueLight ]
         then
           CFGMSG="IBM BlueGene/L"
           MDF=Makefile.defs.bgl-fe
           MDB=Makefile.defs.bgl-be
           MD=${MDB}
           MF=Makefile.cross
         elif [ ${CPU} = "ppc64" -a -d /bgsys/drivers/ppcfloor/hwi ]
         then
           CFGMSG="IBM BlueGene/Q"
           MDF=Makefile.defs.bgq-fe
           MDB=Makefile.defs.bgq-be
           MD=${MDB}
           MF=Makefile.cross
         elif [ ${CPU} = "ppc64" -a -d /bgsys ]
         then
           CFGMSG="IBM BlueGene/P"
           MDF=Makefile.defs.bgp-fe
           MDB=Makefile.defs.bgp-be
           MD=${MDB}
           MF=Makefile.cross
         elif [ ${CPU} = "x86_64" -a -d /opt/FJSVtclang ]
	 then
           CFGMSG="K Computer"
           MDF=Makefile.defs.fx10-fe
           MDB=Makefile.defs.fx10-be
           MD=${MDB}
           MF=Makefile.cross
           ISKCOMPUTER="yes"
         elif [ ${CPU} = "x86_64" -a -d /opt/FJSVfxlang ]
	 then
           CFGMSG="Fujitsu FX10"
           MDF=Makefile.defs.fx10-fe
           MDB=Makefile.defs.fx10-be
           MD=${MDB}
           MF=Makefile.cross
         elif [ ${CPU} = "x86_64" -a -d /opt/intel/mic ]
         then
           CFGMSG="Intel Xeon Phi (MIC)"
           MDF=Makefile.defs.mic-fe
           MDB=Makefile.defs.mic-be
           MD=${MDB}
           MF=Makefile.cross
           ISMIC="yes"
         elif [ ${CPU} = "x86_64" -a -d /opt/cray/xt-asyncpe ]
         then
           ALLOWCOMP="yes"
           . ./utils/build/determine-cc.sh
           case ${COMP} in
             cce) CFGMSG="Cray XT with CCE ${COMPVER} compilers"
                  MDB=Makefile.defs.crayxt-cce-be
                  ;;
             gnu) CFGMSG="Cray XT with GNU ${COMPVER} compilers"
                  MDB=Makefile.defs.crayxt-gnu-be
                  ;;
             intel) CFGMSG="Cray XT with Intel ${COMPVER} compilers"
                  MDB=Makefile.defs.crayxt-intel-be
                  ;;
             pathscale) CFGMSG="Cray XT with PathScale ${COMPVER} compilers"
                  MDB=Makefile.defs.crayxt-pathscale-be
                  ;;
             pgi) CFGMSG="Cray XT with PGI ${COMPVER} compilers"
                  MDB=Makefile.defs.crayxt-pgi-be
                  ;;
             *)   ErrorAndExit "Unexpected Cray XT PrgEnv-compiler '${COMP}'"
                  ;;
           esac
           if [ "${COMP}" != "pgi" -a -z "${BINUTILSDIR}" -a ! -f /usr/include/bfd.h ]
           then
                ErrorAndExit "BFD required; specify --with-binutils"
           fi
           MDF=Makefile.defs.crayxt-fe
           MD=${MDB}
           MF=Makefile.cross
         elif [ ${CPU} = "mips64" -a -d /opt/sicortex ]
         then
           CFGMSG="SiCortex (native)"
           MD=Makefile.defs.sicortex-native
           MF=Makefile.32-64
           if [ -z "${BINUTILSDIR}" -a ! -f /usr/include/bfd.h ]
           then
                ErrorAndExit "BFD required; specify --with-binutils"
           fi
         elif [ -d /SX ]
         then
           CFGMSG="NEC SX"
           MDF=Makefile.defs.necsx-fe
           MDB=Makefile.defs.necsx-be
           MD=${MDB}
           MF=Makefile.cross
           MPINM="sxnm"
         else
           ALLOWCOMP="yes"
           ALLOWMPI="yes"
           if [ -z "${COMP}" ]
           then
             . ./utils/build/select-compiler.sh
           fi
           . ./utils/build/determine-compiler-version.sh
           if [ -z "${MPI}" ]
           then
             if [ "${DISABLE}" != "mpi" -a "${DISABLE}" != "ompi" ]
             then
               . ./utils/build/select-mpi.sh
             fi
           fi
           if [ -z "${MPI}" ]
           then
             if [ "${DISABLE}" = "omp" -o "${DISABLE}" = "ompi" ]
             then
               DISABLE=ompi
             else
               DISABLE=mpi
             fi
             MPI=no
           elif [ ! -f "mf/mpi-${MPI}.def" ]
           then
             ErrorAndExit "Unknown MPI '${MPI}'"
           elif [ "${MPI}" = "sgimpt" ]
           then
             NONSTDMPIEXT="yes"
             EXCL_MPI_DEFS="${EXCL_MPI_DEFS} -DNO_MPI_EXT"
           fi

           CMSG="Linux cluster with"
           case ${COMP} in
             pgi) CFGMSG="${CMSG} PGI ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-pgi
                  ;;
             intel) CFGMSG="${CMSG} Intel ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-intel
                  ;;
             path) CFGMSG="${CMSG} PathScale ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-pathscale
                  ;;
             ibm) CFGMSG="${CMSG} IBM ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-ibm
                  ;;
             sun) CFGMSG="${CMSG} Sun ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-sun
                  ;;
             gomp|gnu) CFGMSG="${CMSG} GNU ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-gnu
                  GFORTRAN=`which gfortran 2> /dev/null`
                  case ${COMPVER} in
                  4.0.*|4.1.*) ;;
                  4.*)         MD=Makefile.defs.linux-gomp
                               GFORTRAN="yes"
                               ;;
                  esac
                  if [ "${NOFOR}" = "yes" ]; then
                      GFORTRAN=""
                  fi
                  ;;
             clang) CFGMSG="${CMSG} clang ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-clang
                  NOFOR=yes
                  ;;
             open64) CFGMSG="${CMSG} Open64 ${COMPVER} compilers and ${MPI} MPI"
                  MD=Makefile.defs.linux-open64
                  ;;
             *)   ErrorAndExit "Unknown compiler '${COMP}'"
                  ;;
           esac
           case ${COMP} in
             gnu|gomp|intel|path|clang)
                  if [ -z "${BINUTILSDIR}" -a ! -f /usr/include/bfd.h ]
                  then
                       ErrorAndExit "BFD required; specify --with-binutils"
                  fi
                  ;;
           esac
         fi

         case ${CPU} in
         x86_64) TAUARCH32=linux
                 TAUARCH64=x86_64
                 ;;
         ppc64)  TAUARCH32=ppc64
                 TAUARCH64=ibm64linux
                 ;;
         ia64)   TAUARCH32=linux
                 TAUARCH64=ia64
                 ;;
         mips64) TAUARCH32=mips
                 TAUARCH64=mips64
                 ;;
         *)      TAUARCH32=linux
                 TAUARCH64=NA
                 ;;
         esac
         ;;
  SunOS) CMSG="Solaris cluster with Sun compilers"
         MD=Makefile.defs.sun
         CPU=`uname -p`
         ALLOWMPI="yes"
         if [ ${CPU} = "sparc" ]
         then
           MF=Makefile.32-64
         fi
         if [ -z "${MPI}" ]
         then
           if [ "${DISABLE}" != "mpi" -a "${DISABLE}" != "ompi" ]
           then
             MPIDIRS=`ls -d /opt/SUNWhpc/HPC?.?`
             NMPIS=`echo "${MPIDIRS}" | wc -l`
             if [ ${NMPIS} -ne 1 ]; then
               CFGecho "INFO: Cannot determine MPI library"
               CFGecho "INFO: Select MPI using --mpi=sun|openmpi"
               CFGecho "INFO: ClusterTools < 7 need \"sun\", ClusterTools >= 7 need \"openmpi\""
               exit 1
             else
               SMPIVER=`echo "${MPIDIRS}" | sed -e 's/^.*HPC\([0-9][0-9]*\).*$/\1/'`
               if [ ${SMPIVER} -lt 7 ]; then
                 MPI=sun
               else
                 MPI=openmpi
               fi
             fi
           fi
         fi
         if [ -z "${MPI}" ]
         then
           if [ "${DISABLE}" = "omp" -o "${DISABLE}" = "ompi" ]
           then
             DISABLE=ompi
           else
             DISABLE=mpi
           fi
           MPI=no
         elif [ ! -f "mf/mpi-${MPI}.def" ]
         then
           ErrorAndExit "Unknown MPI '${MPI}'"
         fi
         CFGMSG="${CMSG} and ${MPI} MPI"
         case ${CPU} in
         sparc)  TAUARCH32=solaris
                 TAUARCH64=solaris-64
                 ;;
         *)      TAUARCH32=sun386i
                 TAUARCH64=sunx86_64
                 ;;
         esac
         ;;
  IRIX64) CFGMSG="SGI cluster with IRIX compilers"
         MD=Makefile.defs.sgi-mips
         MF=Makefile.32-64
         TAUARCH32=sgin32
         TAUARCH64=sgi64
         ;;
  AIX)   . ./utils/build/determine-compiler-version.sh "ibm"
         CFGMSG="AIX cluster with IBM ${COMPVER} compilers"
         MD=Makefile.defs.ibm
         MF=Makefile.32-64
         HASXLCOMP="yes"
         if [ -e /usr/include/swclock.h ]
         then
           if lsdev -l sni0 | grep Available > /dev/null 2>&1
           then
             SWCLOCK=yes
           elif lsdev -l css0 | grep Available > /dev/null 2>&1
           then
             SWCLOCK=yes
           fi
         fi
         TAUARCH32=rs6000
         TAUARCH64=ibm64
         ;;
  UNICOS/mp) CFGMSG="Cray X1 system"
         MD=Makefile.defs.crayx1
         TAUARCH32=NA
         TAUARCH64=crayx1
         ;;
  sn*)   CFGMSG="Cray T3E system"
         MD=Makefile.defs.crayt3e
         TAUARCH32=t3e
         TAUARCH64=NA
         ;;
  Darwin)   CFGMSG="Mac OS X"
         MD=Makefile.defs.Darwin
         TAUARCH32=NA
         TAUARCH64=NA
         ;;

  *)     CFGecho "WARNING: Do not know how to configure system '${SYSTEM}'"
         CFGecho "         Using generic configuration"
         MD=Makefile.defs.generic
         ;;
esac

if grep '^#OMPELGLIB' mf/${MD} > /dev/null 2>&1
then
  CFGecho "INFO: Cannot detect OpenMP support"
  CFGecho ""
  if [ -z "${DISABLE}" ]
  then
    DISABLE=omp
  elif [ ${DISABLE} = "mpi" ]
  then
    DISABLE=ompi
  fi
fi

if [ -n "${COMP}" -a "${ALLOWCOMP}" != "yes" ]
then
  CFGecho "WARNING: Option --compiler=${COMP} not implemented for this platform."
  CFGecho ""
  COMP=""
fi

if [ -n "${MPI}" -a "${ALLOWMPI}" != "yes" ]
then
  CFGecho "WARNING: Option --mpi=${MPI} not implemented for this platform."
  CFGecho ""
  MPI=""
fi

CFGecho "Configuration for ${CFGMSG}"

# handle -force option
if [ -n "${FORCE}" ]
then
  if [ ${FORCE} = "32-64" -o \( ${FORCE} = "basic" -a -n "${PREC}" \) ]
  then
    if grep '^PFLAG *=$' mf/${MD} > /dev/null 2>&1
    then
      CFGecho "- WARNING: ${FRC}-bit compilation mode not yet defined for this platform"
      CFGecho "           Option --force-${FRC} ignored"

      PREC=""
      FRC=""
      FORCE=""
    else
      MF=Makefile.${FORCE}
    fi
  elif [ ${FORCE} = "cross" -a \( -z "${MDF}" -o -z "${MDB}" \) ]
  then
    CFGecho "- WARNING: cross compilation mode not yet defined for this platform"
    CFGecho "           Option --force-cross ignored"
  else
    MF=Makefile.${FORCE}
  fi
fi

# determine default precision
if [ -z "${PREC}" ]
then
  cat > conftest.c <<[[EOT]]
  int main() { return 0; }
[[EOT]]
  cat > Makefile.conftest <<[[EOT]]
include mf/${MD}

conftest: conftest.c
	@\$(CC) conftest.c -o conftest
[[EOT]]
  ${MK} -f Makefile.conftest conftest
  if file conftest | grep 64 > /dev/null 2>&1
  then
    DEFPREC=64
  else
    DEFPREC=32

    # Overwrite default precision to 64 bit on NEC SX
    if [ "${CFGMSG}" = "NEC SX" ]
    then
      DEFPREC=64
    fi
  fi
  PREC=${DEFPREC}
  rm -f conftest.c conftest.o conftest Makefile.conftest
fi

# pdtoolkit
PDTBINDIR=""
if [ -n "${PDTDIR}" ]
then
  if [ -d "${PDTDIR}/${TAUARCH64}" ]
  then
    PDTARCH=${TAUARCH64}
  elif [ -d "${PDTDIR}/${TAUARCH32}" ]
  then
    PDTARCH=${TAUARCH32}
  else
    ErrorAndExit "Cannot find suitable PDToolkit installation (${TAUARCH64}|${TAUARCH32})"
  fi
  PDTBINDIR="${PDTDIR}/${PDTARCH}/bin"
fi


###############################
# Analysis Requirement Checks #
###############################

#--------- GUI toolkits -------
if [ -z "${NOGUI}" ]
then
  . ./utils/build/select-qt.sh
fi


#########################
# Configuration setup   #
#########################
if [ -n "${MDB}" ]
then
  CFG=`echo ${MDB} | sed -e 's/Makefile\.defs\.//' -e 's/-be//'`
elif [ -n "${MD}" ]
then
  CFG=`echo ${MD} | sed -e 's/Makefile\.defs\.//'`
else
  ErrorAndExit "Cannot determine suitable build configuration (Makefile.defs)"
fi
if [ -n "${MPI}" ]
then
  if [ ${MPI} = "no" ]; then CFG="${CFG}-nompi"; else CFG="${CFG}-${MPI}"; fi
fi
case ${MF} in
  Makefile.basic) case ${FRC} in
                    32-64|32|64) CFG="${CFG}-${FRC}" ;;
                  esac
                  ;;
  Makefile.32-64) CFG="${CFG}-32-64"
                  ;;
esac

BDIR="build-${CFG}"
if [ -d ${BDIR} -o -f ${BDIR} ]
then
  echo "WARNING: Old configuration found (${BDIR})."
  echo "Continue and replace (y/n) ?"
  read ANSWER
  if [ "${ANSWER}x" != "yx" ]
  then
    exit 1
  else
    rm -rf ${BDIR}
    echo ""
  fi
fi
CFGecho "- Setting up build configuration (${BDIR})"
mkdir ${BDIR}
cd ${BDIR}


#########################
# Package configuration #
#########################

# Generate files using templates
if [ -n "${MD}" ]
then
  CFGecho "- Generating GNUmakefile (using ${MF})"
  ln -s ../utils/build/${MF} GNUmakefile || exit 1
  ln -s ../utils/build/Makefile.redirect Makefile
  if [ -z "${MDF}" ]
  then
    CFGecho "- Generating Makefile.defs (using ${MD} + optional.defs + gui.defs)"
    cp ../mf/${MD} Makefile.defs || exit 1
    cat ../mf/optional.defs >> Makefile.defs
    cat ../mf/gui.defs >> Makefile.defs
    ConfigGNUmake >> Makefile.defs
    cp ../mf/qt.pro.defs . || exit 1
  fi
fi

if [ -n "${MDF}" ]
then
  CFGecho "- Generating Makefile.defs.fe (using ${MDF} + optional.defs + gui.defs)"
  cp ../mf/${MDF} Makefile.defs.fe || exit 1
  echo ""            >> Makefile.defs.fe
  if [ -z "${ISMIC}" ]
  then
      echo "SYSKIND=fe"  >> Makefile.defs.fe
  fi
  echo ""            >> Makefile.defs.fe
  cat ../mf/optional.defs >> Makefile.defs.fe
  cat ../mf/gui.defs >> Makefile.defs.fe
  ConfigGNUmake >> Makefile.defs.fe
  cp ../mf/qt.pro.defs . || exit 1
  CFGecho "- Generating Makefile.defs.be (using ${MDB})"
  cp ../mf/${MDB} Makefile.defs.be || exit 1
  echo ""            >> Makefile.defs.be
  if [ -z "${ISMIC}" ]
  then
      echo "SYSKIND=be"  >> Makefile.defs.be
  else
      echo "SYSKIND=mic" >> Makefile.defs.be
  fi
  echo ""            >> Makefile.defs.be
  cat ../mf/optional.defs >> Makefile.defs.be
  ConfigGNUmake >> Makefile.defs.be
fi

# Final MPI config
if [ "${DISABLE}" != "mpi" -a "${DISABLE}" != "ompi" ]
then
  if [ -z "${MDF}" ]
  then
    echo "include Makefile.defs" > Makefile.conftest
    MPILIB=`grep '^MPILIB ' Makefile.defs \
           | sed -e 's/^.*= *//' -e 's/ .*$//' -e 's/-l//' | tr -d '\n'`
     MPICC=`grep '^MPICC '  Makefile.defs \
           | sed -e 's/^.*= *//' -e 's/ .*$//' | tr -d '\n'`
  else
    echo "include Makefile.defs.be" > Makefile.conftest
    MPILIB=`grep '^MPILIB ' Makefile.defs.be \
           | sed -e 's/^.*= *//' -e 's/ .*$//' -e 's/-l//' | tr -d '\n'`
     MPICC=`grep '^MPICC '  Makefile.defs.be \
           | sed -e 's/^.*= *//' -e 's/ .*$//' | tr -d '\n'`
  fi
  if [ -n "${MPI}" ]
  then
    if [ -f "../mf/mpi-${MPI}.def" ]
    then
      echo "include ../mf/mpi-${MPI}.def" >> Makefile.conftest
      MPILIB=`grep '^MPILIB ' ../mf/mpi-${MPI}.def \
             | sed -e 's/^.*= *//' -e 's/ .*$//' -e 's/-l//' | tr -d '\n'`
       MPICC=`grep '^MPICC '  ../mf/mpi-${MPI}.def \
             | sed -e 's/^.*= *//' -e 's/ .*$//' | tr -d '\n'`
    fi
  fi
  # use default MPI library name if not set
  if [ -z "${MPILIB}" ]
  then
    MPILIB=mpi
  fi
  PMPILIB="libp${MPILIB}"
  MPILIB="lib${MPILIB}"

  cat >> Makefile.conftest <<[[EOT]]

conftest: conftest.c
	@\$(MPICC) -E conftest.c | grep '/mpi.h"' | head -1 > mpiconf1.txt
	@\$(MPICC) -E conftest.c > mpiconf2.txt
[[EOT]]

  # Determine location of mpi.h and MPI library
  cat > conftest.c <<[[EOT]]
#include <mpi.h>
#ifdef ROMIO_VERSION
MPIO_Request mior;
#endif
[[EOT]]
  ${MK} -f Makefile.conftest conftest
  MPIINCDIR=`cat mpiconf1.txt | sed -e 's#^.* "##' -e 's#/mpi.h".*##'`
  if grep '^MPIO_Request mior;$' mpiconf2.txt > /dev/null 2>&1
  then
    NONSTDMPIO="yes"
    EXCL_MPI_DEFS="${EXCL_MPI_DEFS} -DNO_MPI_IO"
  fi
  rm -f conftest.c Makefile.conftest mpiconf1.txt mpiconf2.txt
  
  if [ -n "${MPIINCDIR}" ]
  then
    MPIDIR=`dirname ${MPIINCDIR}`
    # IBM POE's MPI header files are sometimes located one directory
    # level deeper than usual...
    if [ "`basename ${MPIDIR}`" = "include" -a "${MPI}" = "ibmpoe" ]
    then
      MPIDIR=`dirname ${MPIDIR}`
    fi
    MPILIBDIR="${MPIDIR}/lib"
    MPILIB64DIR="${MPIDIR}/lib64"
    PDTMPIINC="-I${MPIINCDIR}"

    if [ ! -d "${MPILIBDIR}" -a ! -d "${MPILIB64DIR}" ]
    then
      MPICMD=`which ${MPICC} 2> /dev/null`
      MPIBINDIR=`dirname ${MPICMD}`
      MPIDIR=`dirname ${MPIBINDIR}`
      MPILIBDIR="${MPIDIR}/lib"
      MPILIB64DIR="${MPIDIR}/lib64"
    fi

    for ml in \
        ${MPILIB64DIR}/${PMPILIB}.a        ${MPILIB64DIR}/${PMPILIB}.so \
        ${MPILIB64DIR}/${MPILIB}.a         ${MPILIB64DIR}/${MPILIB}.so \
        ${MPILIBDIR}/lib64/${PMPILIB}.a    ${MPILIBDIR}/lib64/${PMPILIB}.so \
        ${MPILIBDIR}/lib64/${MPILIB}.a     ${MPILIBDIR}/lib64/${MPILIB}.so \
        ${MPILIBDIR}/libmpi64/${PMPILIB}.a ${MPILIBDIR}/libmpi64/${PMPILIB}.so \
        ${MPILIBDIR}/libmpi64/${MPILIB}.a  ${MPILIBDIR}/libmpi64/${MPILIB}.so \
        ${MPILIBDIR}/${PMPILIB}.a          ${MPILIBDIR}/${PMPILIB}.so \
        ${MPILIBDIR}/${MPILIB}.a           ${MPILIBDIR}/${MPILIB}.so \
        ${MPILIBDIR}/libmpi/${PMPILIB}.a   ${MPILIBDIR}/libmpi/${PMPILIB}.so \
        ${MPILIBDIR}/libmpi/${MPILIB}.a    ${MPILIBDIR}/libmpi/${MPILIB}.so \
        ${MPILIBDIR}/linux_amd64/${PMPILIB}.a   ${MPILIBDIR}/linux_amd64/${PMPILIB}.so \
        ${MPILIBDIR}/linux_amd64/${MPILIB}.a    ${MPILIBDIR}/linux_amd64/${MPILIB}.so \
        ${MPILIBDIR}/linux_ia32/${PMPILIB}.a   ${MPILIBDIR}/linux_ia32/${PMPILIB}.so \
        ${MPILIBDIR}/linux_ia32/${MPILIB}.a    ${MPILIBDIR}/linux_ia32/${MPILIB}.so \
        ${MPILIBDIR}/${MPILIB}.dylib \
        NOT-FOUND
    do
      if [ -r "${ml}" ]
      then
        MPILIB="${ml}"
        break
      fi
    done
    if [ ${ml} = "NOT-FOUND" ]
    then
      MPILIB=""
    fi
  else
    PDTMPIINC=""
  fi

  # call script to configure MPI adapter
  . ../utils/build/config-mpi.sh

fi


# Transform generated files based on configuration determined
if [ -z "${MDF}" ]
then
  CF=Makefile.defs
  . ../utils/build/config-makedefs.sh
  ECXX=`grep '^ECXX ' Makefile.defs | sed -e 's/^.*= //' -e 's/ .*$//' | tr -d '\n'`
else
  CF=Makefile.defs.fe
  . ../utils/build/config-makedefs.sh
  CF=Makefile.defs.be
  . ../utils/build/config-makedefs.sh
  ECXX=`grep '^ECXX ' Makefile.defs.fe | sed -e 's/^.*= //' -e 's/ .*$//' | tr -d '\n'`
fi

# add MPIEXTRA options to ${CF}
sed -e "s/^\(MPIEXTRA.*\)$/\1 ${EXCL_MPI_DEFS}/" ${CF} > sed.out \
    && mv sed.out ${CF} || exit 1

# Configure Vampir integration via dbus
if [ -z "${NOGUI}" ]
then
  if [ -n "${QT}" ]
  then
    HASDBUS=`pkg-config --list-all 2>/dev/null | grep ^dbus-1 `
    if [ -n "${HASDBUS}" ]
    then
      DBUSVER=`pkg-config --modversion dbus-1`
      case "${DBUSVER}" in
        0.*) ;; # too old
        1.*) DBUSINC=`pkg-config --cflags-only-I dbus-1 | sed -e 's/-I//g' -e 's/ /%/g'`
             DBUSLIB=`pkg-config --libs dbus-1 | sed -e 's/ /%/g'`
             DBUSLOC=`echo ${DBUSINC} | sed -e 's#^.*%/#/#' -e 's#/include%*$##'`
             CFGecho "- Configuring DBUS-1 (using ${DBUSLOC} ${DBUSVER})"
             sed -e 's,^#VAMPIR_,VAMPIR_,' -e 's,^#TB_,TB_,' \
                 -e 's,^VAMPIR_DBUS_INCLUDEPATH.*$,VAMPIR_DBUS_INCLUDEPATH = '${DBUSINC}',' \
                 -e 's,^VAMPIR_DBUS_LIBS.*$,VAMPIR_DBUS_LIBS = '${DBUSLIB}',' \
                 -e 's,%, ,g' \
                 qt.pro.defs > sed.out && mv sed.out qt.pro.defs || exit 1
             ;;
          *) echo "- IGNORING dbus-1 version ${DBUSVER}" ;;
      esac
    fi

    # Configure Paraver integration via config file
    if [ -n "${PRVCFG}" ]
    then
      CFGecho "- Configuring Paraver Integration (using ${PRVCFG})"
      sed -e 's,^#PV_,PV_,' -e 's,^#TB_,TB_,' \
          -e 's,^PV_DEF_CFG.*$,PV_DEF_CFG = '${PRVCFG}',' \
          -e 's,%, ,g' \
          qt.pro.defs > sed.out && mv sed.out qt.pro.defs || exit 1
    fi
  fi
fi

# Apply var=value change requests
for SSUF in "" ".fe" ".be"
do
  if [ -s ${CFGSEDSCRIPT}${SSUF} -a -w Makefile.defs${SSUF} ]
  then
    sed -f ${CFGSEDSCRIPT}${SSUF} Makefile.defs${SSUF} > sed.out && \
        mv sed.out Makefile.defs${SSUF} || exit 1
    rm -f ${CFGSEDSCRIPT}${SSUF}
  fi
done


########################
# Print final comments #
########################

if [ "${MF}" = "Makefile.32-64" -a -n "${LIBS}" ]
then
  CFGecho ""
  CFGecho "NOTE: Configured for automatic 32-bit/64-bit installation"
  CFGecho "      but you specified to use the external packages:${LIBS}"
  CFGecho "      Please make sure that"
  CFGecho "      - These packages are available in 32-bit and 64-bit versions"
  CFGecho "      - The Makefile.defs settings for these packages matches the installation"
fi

if [ "${MF}" = "Makefile.cross" -a -n "${LIBS}" ]
then
  CFGecho ""
  CFGecho "NOTE: Configured for automatic frontend/backend installation"
  CFGecho "      but you specified to use the external packages:${LIBS}"
  CFGecho "      Please make sure that"
  if [ -n "${PAPIDIR}" ]
  then
    CFGecho "      - PAPI is available for the backend measurement libraries"
  fi
  if [ -n "${VTF3DIR}" ]
  then
    CFGecho "      - VTF3 is available for the frontend converters"
  fi
  if [ -n "${OTFDIR}" ]
  then
    CFGecho "      - OTF is available for both architectures"
  fi
  CFGecho "      - The Makefile.defs.fe and Makefile.defs.be settings"
  CFGecho "        for these packages matches the installation"
fi

if [ -z "${NOGUI}" ]
then
  qtComments
fi

if [ -z "${HYBRID}" -a -z "${DISABLE}" ]
then
  CFGecho ""
  CFGecho "NOTE: Building of hybrid MPI/OpenMP analysis component disabled"
  CFGecho "      due to known problems with ${COMP} v${COMPVER} compilers."
fi

if [ -n "${PDTBINDIR}" -a ! -x "${PDTBINDIR}/tau_instrumentor" ]
then
  CFGecho ""
  CFGecho "NOTE: Non-standard installation of PDToolkit found"
  CFGecho "      Please fix variable PDTBIN in ${BDIR}/Makefile.defs"
  CFGecho "      to point to suitable directory which contains tau_instrumentor"
fi

if [ -n "${HASXLCOMP}" ]
then
  if [ ${XLC_MAJOR} -ge 11 ]
  then
    CFGecho ""
    CFGecho "NOTE: Using new IBM compiler instrumentation interface"
    CFGecho "      This interface is incompatible with XLC/XLF < 11/13, but"
    CFGecho "      has a significantly lower runtime overhead. If you need"
    CFGecho "      compatibility with older compiler versions, you need to"
    CFGecho "      compile Scalasca with XLC/XLF < 11/13 (and/or provide two"
    CFGecho "      installations of Scalasca to take advantage of the lower"
    CFGecho "      overhead interface for the new compilers)."
  else
    CFGecho ""
    CFGecho "NOTE: Using old IBM compiler instrumentation interface"
    CFGecho "      This interface will work with any XLC/XLF > 7.1.1/9.1.1."
    CFGecho "      A new interface with significantly lower overhead will be"
    CFGecho "      used when compiling Scalasca with XLC/XLF >= 11/13, but"
    CFGecho "      such an installation will then be incompatible with older"
    CFGecho "      compiler versions."
  fi
fi

#Save configuration info
echo "% $0 $@" > configure.log
echo "" >> configure.log
cat ${LOGFILE} >> configure.log
#save log annex
if [ -f ${LOG_ANNEX} ]; then
  cat ${LOG_ANNEX} >> configure.log
fi
rm -f ${LOGFILE} ${LOG_ANNEX} 

echo ""
echo "####################################################################"
echo "CONFIGURATION COMPLETE"
echo ""
echo "Next steps:"
echo " - cd ${BDIR}"
if [ -n "${MDF}" ]
then
echo " - [optional] Edit Makefile.defs.fe/be for further configuration"
else
echo " - [optional] Edit Makefile.defs for further configuration"
fi
echo " - ${MK}"
echo " - ${MK} install"
echo "####################################################################"

exit 0
