#!/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_CC=${MPITRAMPOLINE_CC:-/opt/bin/armv7l-linux-gnueabihf-libgfortran4-cxx11-mpi+mpitrampoline/arm-linux-gnueabihf-gcc}
MPITRAMPOLINE_CFLAGS=${MPITRAMPOLINE_CFLAGS:-}

case "$1" in
    -showme:command)
        echo "$MPITRAMPOLINE_CC $MPITRAMPOLINE_CFLAGS"
        exit 0
        ;;
    -showme:compile)
        echo "$MPITRAMPOLINE_CFLAGS -I/workspace/destdir/include"
        exit 0
        ;;
    -showme:link)
        echo "$MPITRAMPOLINE_CFLAGS -L/workspace/destdir/lib -Wl,-rpath,/workspace/destdir/lib -lmpitrampoline -ldl"
        exit 0
        ;;
    -showme:incdirs)
        echo "/workspace/destdir/include"
        exit 0
        ;;
    -showme:libdirs)
        echo "/workspace/destdir/lib"
        exit 0
        ;;
    -showme:libs)
        echo "-lmpitrampoline -ldl"
        exit 0
        ;;
    -showme:version)
        echo "MPItrampoline 4.0.2"
        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_CC $MPITRAMPOLINE_CFLAGS -I/workspace/destdir/include  -L/workspace/destdir/lib -Wl,-rpath,/workspace/destdir/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_CC $MPITRAMPOLINE_CFLAGS -I/workspace/destdir/include "$@"
elif [ $add_rpath != true ]; then
    exec $MPITRAMPOLINE_CC $MPITRAMPOLINE_CFLAGS -I/workspace/destdir/include  -L/workspace/destdir/lib "$@" -lmpitrampoline -ldl
else
    exec $MPITRAMPOLINE_CC $MPITRAMPOLINE_CFLAGS -I/workspace/destdir/include  -L/workspace/destdir/lib -Wl,-rpath,/workspace/destdir/lib "$@" -lmpitrampoline -ldl
fi
