#!/bin/bash
#
# Generate some make file dependency entries for a Fortran 90 file that employs "use".
#
# For every "use" statement, generate a dependency on lowercase(modulename).o
#
# Note: We assume that the name of a module and the same of source are the same.
#       The name of the source file should be all lower case (except for the extension).

# set defaults
FS=f
FS90=f90

# process option arguments
key_prev=
for key in "$@" ; do

    # If the previous option needs an argument, assign it.
    if test -n "$key_prev"; then
	    eval "$key_prev=\$key"
	    key_prev=
	    continue
    fi

    case $key in
    -fs)
        key_prev='FS'
        ;;
    -fs=*)
        FS="${key#*=}"
        ;;
    -fs90)
        key_prev='FS90'
        ;;
    -fs90=*)
        FS90="${key#*=}"
        ;;
    *)
        echo "f90mkdepend: Unknown option: $key"
        exit 1
        ;;
    esac
done

# don't complain if *.F90 doesn't match any files
shopt -s nullglob

cat /dev/null > f90mkdepend.log

# append module dependencies to Makefile
for filename in *.F90 *.F *.h; do
  # quick check for "use" to speed up processing
  if grep -i '^ *use ' $filename > /dev/null; then
    # extract module name in lower case
    modreflist=$(grep -i '^ *use ' $filename | awk '{print tolower($2)}' | sed -e 's/,.*$//' -e 's/\r$//')

    echo "$filename => $modreflist" >> f90mkdepend.log

    # change .F90 into .$FS90, .F into .$FS for target
    preprocessed=$(echo $filename | sed -e "s/\.F$/.$FS/" -e "s/\.F90$/.$FS90/")

    depline="$preprocessed:"
    for m in $modreflist; do
      # ignore modules that don't have an appropriately named source file
      if [ -f $m.F90 ] || [ -f $m.F ]; then
        depline="$depline $m.o"
      elif [ -f ${m%_mod}.F90 ] || [ -f ${m%_mod}.F ]; then
        # source file name is module name without "_mod"
        depline="$depline ${m%_mod}.o"
      else
        echo "WARNING: f90mkdepend: in $filename no source file found for module $m" 1>&2
      fi
    done
    echo $depline
  fi
done
