#!/bin/sh

# We choose to behave like OpenMPI in this respect.
#
# All OpenMPI versions support "-showme". Modern OpenMPI version also
# support "-showme:compile" and "-showme:link".
#
# MPICH supports "-compile-info" and "-link-info".

MPITRAMPOLINE_FC=${MPITRAMPOLINE_FC:-/usr/bin/f95}
MPITRAMPOLINE_FCFLAGS=${MPITRAMPOLINE_FCFLAGS:- -fallow-argument-mismatch -fcray-pointer}

case "$1" in
    -showme:command)
        echo "$MPITRAMPOLINE_FC"
        exit 0
        ;;
    -showme:compile)
        echo "$MPITRAMPOLINE_FCFLAGS -I/opt/mpitrampoline/include"
        exit 0
        ;;
    -showme:link)
        echo "$MPITRAMPOLINE_FCFLAGS -L/opt/mpitrampoline/lib -Wl,-rpath,/opt/mpitrampoline/lib -lmpitrampoline -ldl"
        exit 0
        ;;
    -showme:incdirs)
        echo "/opt/mpitrampoline/include"
        exit 0
        ;;
    -showme:libdirs)
        echo "/opt/mpitrampoline/lib"
        exit 0
        ;;
    -showme:libs)
        echo "-lmpitrampoline -ldl"
        exit 0
        ;;
    -showme:version)
        echo "MPItrampoline 5.4.0"
        echo "MPI trampoline"
        echo "https://github.com/eschnett/MPItrampoline"
        exit 0
        ;;
    -showme:help)
        echo "$0 {-showme:{command|compile|link|incdirs|libdirs|libs|version|help}|-show*} args"
        exit 0
        ;;
    -show*)
        echo "$MPITRAMPOLINE_FC $MPITRAMPOLINE_FCFLAGS -I/opt/mpitrampoline/include  -L/opt/mpitrampoline/lib -Wl,-rpath,/opt/mpitrampoline/lib -lmpitrampoline -ldl"
        exit 0
        ;;
esac

# Are we linking?
linking=true
for arg in "$@"; do
    if [ "$arg" = "-E" ] || [ "$arg" = "-c" ] || [ "$arg" = "-S" ]; then
        linking=false
        break
    fi
done

# Can we use rpath? (The Darwin linker has an '-r' argument that
# merges object files together. It does not work with '-rpath'.)
add_rpath=true
for arg in "$@"; do
    if [ "$arg" = "-r" ] || [ "$arg" = "-Wl,-r" ]; then
        add_rpath=false
        break
    fi
done

if [ $linking != true ]; then
    exec $MPITRAMPOLINE_FC $MPITRAMPOLINE_FCFLAGS -I/opt/mpitrampoline/include "$@"
elif [ $add_rpath != true ]; then
    exec $MPITRAMPOLINE_FC $MPITRAMPOLINE_FCFLAGS -I/opt/mpitrampoline/include  -L/opt/mpitrampoline/lib "$@" -lmpitrampoline -ldl
else
    exec $MPITRAMPOLINE_FC $MPITRAMPOLINE_FCFLAGS -I/opt/mpitrampoline/include  -L/opt/mpitrampoline/lib -Wl,-rpath,/opt/mpitrampoline/lib "$@" -lmpitrampoline -ldl
fi
