#!/bin/bash
######################################################################################
#
# This script gets the gfc compiler and the corresponding library directory.
#
# Author: Zachary Matthews
# Since:  NextMidas 4.2.0
#
######################################################################################

fc="-1"

function check_gfc_cmd {
  gfc_cmd=$1
  if [ -x `command -v $gfc_cmd` ] && [ "$fc" == "-1" ] ; then
    $gfc_cmd -fdec 2>&1 | grep -i "warning\|unrecognized\|unknown\|unsupported" > /dev/null
    [ "$?" == "1" ] && fc=$gfc_cmd
  fi
}

# Give preference to gfortran
check_gfc_cmd "gfortran"

# Check gfc-gfortran if gfortran not installed or does not take DEC extensions
check_gfc_cmd "gfc-gfortran"

echo $fc

# Exit if no version of gfc-gfortran or gfortran is installed or does not take DEC extensions
[ "$fc" == "-1" ] && exit 1

fc_path=`which $fc`
if [[ "$fc_path" == "/usr/bin/"* ]] ; then
  fc_root=`dirname $fc_path`
  libdir=`echo $fc_root | sed 's/bin/lib\/gcc/'`
  libdir="$libdir/`$fc -dumpmachine`/`$fc -dumpversion`/"
else
  libdir="/usr/lib/gcc/`$fc -dumpmachine`/`$fc -dumpversion`/"
fi
echo $libdir
