#!/bin/bash

set -ex

# configure balks if F90 is defined
# with a fatal deprecation message pointing to FC
unset F90 F77

export FCFLAGS="$FFLAGS"

# avoid absolute-paths in compilers
export CC=$(basename "$CC")
export CXX=$(basename "$CXX")
export FC=$(basename "$FC")

if [[ "$(uname)" == "Darwin" ]]; then
    # Fix perl locale settings on osx
    export LANGUAGE=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    export LANG=en_US.UTF-8
    export LC_CTYPE=en_US.UTF-8
fi

if [[ $target_platform == osx-arm64 ]]; then
    
    list_config_to_patch=$(find . -name config.guess | sed -E 's/config.guess//')
    for config_folder in $list_config_to_patch; do
        echo "copying config to $config_folder ...\n"
        cp -v $BUILD_PREFIX/share/libtool/build-aux/config.* $config_folder
    done
fi

if [[ "$target_platform" == "linux-ppc64le" ]]; then
    # Fix symbol relocation errors
    export CFLAGS="$CFLAGS -fplt"
    export CXXFLAGS="$CXXFLAGS -fplt"
fi

# avoid recording flags in compilers
# See Compiler Flags section of MPICH readme
# TODO: configure ignores MPICHLIB_LDFLAGS
export MPICHLIB_CPPFLAGS=$CPPFLAGS
unset CPPFLAGS
export MPICHLIB_CFLAGS=$CFLAGS
unset CFLAGS
export MPICHLIB_CXXFLAGS=$CXXFLAGS
unset CXXFLAGS
export MPICHLIB_LDFLAGS=$LDFLAGS
unset LDFLAGS
export MPICHLIB_FFLAGS=$FFLAGS
unset FFLAGS
export MPICHLIB_FCFLAGS=$FCFLAGS
unset FCFLAGS

# set some specific flags that we *do* want recorded in the compilers
# only the bare minimum of prefix-awareness here
export CPPFLAGS="-I$PREFIX/include"
export CFLAGS="-I$PREFIX/include"
export CXXFLAGS="-I$PREFIX/include"
export FFLAGS="-I$PREFIX/include"
export FCFLAGS="-I$PREFIX/include"
export LDFLAGS="-L$PREFIX/lib -Wl,-rpath,$PREFIX/lib"

export LIBRARY_PATH="$PREFIX/lib"
export MPICH_AUTOTOOLS_DIR="${BUILD_PREFIX}/bin"

# Allow argument mismatch in Fortran
# https://github.com/pmodels/mpich/issues/4300
export FFLAGS="$FFLAGS -fallow-argument-mismatch"
export FCFLAGS="$FCFLAGS -fallow-argument-mismatch"

./autogen.sh

./configure --prefix=$PREFIX \
            --disable-dependency-tracking \
            --disable-libxml2 \
            --enable-romio \
            --enable-shared \
            --enable-cxx \
            --enable-fortran \
            --disable-wrapper-rpath

make -j"${CPU_COUNT:-1}"
make install
