#! /bin/sh
#
#  gather in one shell script the build of an OBJ file (*.o), without
#  modifying the timestamp of the corresponding MOD file (*.mod) if its
#  content has not been changed.
#
#  Requirements:
#   1) the source file name is put on the line command just after the
#      '-c' flag;
#   2) the file name must match the module name;
#   3) each source file contains at most one module.
#
#  usage:
#    executing: ifort [options] -c source.f90 [other args]
#
#  É. Canot -- IPR/CNRS -- September 1st, 2011
#
#-----------------------------------------------------------------------

if [ $# -lt 3 ]; then
  echo
  echo "  usage:"
  echo "    `basename $0` ifort [options] -c source.f90 [other args]"
  echo
  exit 1
fi

# copy of all args
ARGS=$*

F90C=$1
shift

# find the source file, located after the '-c' option flag
while [ "$1" != "-c" ]; do
  shift;
  if [ $# -eq 0 ]; then
    echo "compile command: cannot find '-c' flag!"
    exit 1
  fi
done
shift

# source file suffixes may be '.f90' or '.F90'
BASE=`basename $1 .f90`
MODULE=`basename $BASE .F90`.mod

if [ -f inc_dev/$MODULE ]; then
  mv inc_dev/$MODULE inc_dev/$MODULE~
fi

# doing the required compiler action
$ARGS
COMPILE_STATUS=$?

if [ $COMPILE_STATUS -eq 0 ]; then
  if [ -f inc_dev/$MODULE~ ]; then
    if ./cmp_ifort_mod -s inc_dev/$MODULE inc_dev/$MODULE~ ; then
      mv inc_dev/$MODULE~ inc_dev/$MODULE
    else
      rm inc_dev/$MODULE~
    fi
  fi
else
  # compilation failed: we must remove old MOD file
  rm inc_dev/$MODULE~
fi

