#!/usr/bin/env -S -u LD_PRELOAD /bin/sh
here=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
real=${REAL_FC:-}
if [ -z "$real" ]; then
  old_ifs=$IFS
  IFS=:
  for dir in $PATH; do
    [ "$dir" = "$here" ] && continue
    if [ -x "$dir/gfortran" ]; then
      real=$dir/gfortran
      break
    fi
  done
  IFS=$old_ifs
fi
if [ -z "$real" ]; then
  echo "gfortran is not on PATH" >&2
  exit 1
fi
unset LD_PRELOAD
# conda gfortran's ld cannot link libclang_rt.tsan: that library needs
# GLIBC_2.34 and the conda sysroot does not provide it. A program that
# only reaches the runtime through libseams's DT_NEEDED segfaults at
# startup. Compile Fortran with gfortran, then link with clang so the
# executable itself needs the shared thread runtime.
if [ -n "${TSAN_RUNTIME:-}" ] && [ -f "$TSAN_RUNTIME" ]; then
  link=1
  for arg in "$@"; do
    case $arg in
      -c|-E|-M|-MM) link=0 ;;
    esac
  done
  if [ "$link" = 1 ]; then
    rtdir=$(dirname "$TSAN_RUNTIME")
    out=
    cflags=
    objs=
    lflags=
    skip=
    for arg in "$@"; do
      if [ -n "$skip" ]; then
        case $skip in
          o) out=$arg ;;
          I) cflags="$cflags -I $arg" ;;
          J) cflags="$cflags -J $arg" ;;
        esac
        skip=
        continue
      fi
      case $arg in
        -o) skip=o ;;
        -I) skip=I ;;
        -J) skip=J ;;
        -I*|-J*|-D*|-f*|-std=*|-cpp|-fopenmp) cflags="$cflags $arg" ;;
        *.f90|*.F90|*.f|*.F|*.for)
          obj=$(mktemp --suffix=.o)
          # shellcheck disable=SC2086
          "$real" -c $cflags "$arg" -o "$obj" || exit 1
          objs="$objs $obj"
          ;;
        *) lflags="$lflags $arg" ;;
      esac
    done
    # clang does not search conda gfortran's private lib directory.
    glib=$("$real" -print-file-name=libgfortran.so)
    glibdir=$(dirname "$glib")
    # clang -fopenmp asks for libomp, which lives next to Archer.
    omplib=
    if [ -n "${OMP_TOOL_LIBRARIES:-}" ] && [ -f "$OMP_TOOL_LIBRARIES" ]; then
      omplib=$(dirname "$OMP_TOOL_LIBRARIES")
    fi
    # shellcheck disable=SC2086
    exec clang -fsanitize=thread -shared-libsan -Wl,-rpath,"$rtdir" \
      -L"$glibdir" -Wl,-rpath,"$glibdir" \
      ${omplib:+-L"$omplib" -Wl,-rpath,"$omplib"} \
      ${out:+-o "$out"} $objs $lflags -lgfortran
  fi
fi
exec "$real" "$@"
