#!/bin/sh
# appends module dependencies to the end of a partially completed makefile
# call this from makefile with argument "$(SRCS)"
Makefile=Makefile

SRCS=${1}
#echo "SRCS=${SRCS}"

# remove old deps, if any
begin=$(egrep -n "^#deps" ${Makefile} | awk -F : '{ print $1 }')
end=$(egrep -n "^#end deps" ${Makefile} | awk -F : '{ print $1 }')
#echo begin=${begin}
#echo end=${end}
# This could use some refinement
if [ "${begin}" ]; then
  if [ "${end}" ]; then
    if [ ${begin} -lt ${end} ]; then
      new=$(sed "${begin}","${end}"d ${Makefile})
      echo "${new}" > ${Makefile} 
    fi
  fi
fi

echo "Building dependency list..."

# add line to Makefile showing where deps start
echo "" >> ${Makefile}
echo "#deps" >> ${Makefile}

# scan each source file for use statements and store module names
for file in ${SRCS}; do
#  echo "file=${file}"
  # look for use statements & isolate the module name & elim duplicates
  # **need to allow for upper case here 
  MODS=$(awk '/^[:blank:]*use +/ { print $2 }' ${file} | \
    sed 's/,/ /g' | sort | uniq)
  # just to reformat
  MODS=$(echo ${MODS})
#  echo "MODS=${MODS}"
  # At this point MODS contains the modules that $file depends on directly.
  # Not sure if we need to include indirect dependcies.  I think make can
  # do indirect part itself.

  # scan each source file for that module definition
  dep_list=""
  for module in ${MODS}; do
    for src_file in ${SRCS}; do
#      echo "about to get match"
      # egrep may be best here, just an experiment
#      echo "module=${module}"
#      echo "src_file=${src_file}"
# can't get this to do what I want using ${module} in the awk regex
      name=$(awk '/^[:blank:]*module +/ { print $2 }' ${src_file}) 
#      echo "name=${name}"
      # do we need to worry about whitespace here?
      if [ "${name}" = "${module}" ]; then
        # the ${file} directly depends on the ${src_file}
        # need to replace the .f90 with .o here --use sed
        obj_file=$(echo ${src_file} | sed 's/.f90$/.o/')
        dep_list="${dep_list} ${obj_file}"
#        echo "dep_list=${dep_list}"
      fi
    done
  done
  # remove extra whitespace
  dep_list=$(echo ${dep_list} | sed 's/^[:blank:]+//g' | \
    sed 's/[:blank:]+/ /g')
  #echo "dep_list=${dep_list}"

  # now add a line to Makefile with the deps
  if [ "${dep_list}" != "" ]; then
    o_file=$(echo ${file} | sed 's/.f90$/.o/')
    line=${o_file}" : "${dep_list}
    echo "${line}"
    echo "${line}" >> ${Makefile}
  fi
done

# echo a line to indicate end of deps
echo "#end deps" >> ${Makefile}

echo "Dependency list added to ${Makefile}"
