#!/bin/sh
#-----------------------------------------------------------------------------
# depend: Produce a dependency list for AIPS++ classes
#-----------------------------------------------------------------------------
#
#   Copyright (C) 1992-2004
#   Associated Universities, Inc. Washington DC, USA.
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   Correspondence concerning AIPS++ should be addressed as follows:
#          Internet email: aips2-request@nrao.edu.
#          Postal address: AIPS++ Project Office
#                          National Radio Astronomy Observatory
#                          520 Edgemont Road
#                          Charlottesville, VA 22903-2475 USA
#
#-----------------------------------------------------------------------------
# Usage: depend -p package[-module] file1 [file2...]
#-----------------------------------------------------------------------------
# depend produces a list of dependencies of AIPS++ classes with respect to
# their included header files.  It produces a "$PACKAGE.time" file for the
# package which may be used to determine which C++ header and implementation
# files need to be processed to bring the "$PACKAGE.list" dependency list up
# to date.  These files are kept in $ARCHAUXD.
#
# depend is normally invoked by the "implement" makefile as part of the
# process of updating the makefile's included files.  The list of files passed
# to depend in that case consists of all ".cc" and ".h" files newer than the
# ".time" timestamp file produced by depend.  Invoking depend manually with an
# incomplete list of files could invalidate the dependency analysis.
#
# The C++ header and implementation files may be specified in full or in
# brief, for example, in full:
#
#     /aips++/code/aips/implement/Foo.cc
#     /aips++/code/aips/implement/Foo.h
#     /aips++/code/include/aips/Foo.cc
#     /aips++/code/include/aips/Foo.h
#
#     /aips++/code/aips/implement/module/Bar.cc
#     /aips++/code/aips/implement/module/Bar.h
#     /aips++/code/include/aips/module/Bar.cc
#     /aips++/code/include/aips/module/Bar.h
#
# or in brief:
#
#     Foo.cc
#     aips/Foo.h
#
#     module/Bar.cc
#     aips/module/Bar.h
#
# Note that the implementation files must correspond to the package-module
# combination specified via the "-p" option, but the header files may belong
# to any package and so must have a package name associated with them. 
#
# Options:
#   -p package[-module]
#                The AIPS++ package-module combination.  There is no default
#                for the package name.  An empty module name indicates the
#                "implement" directory itself.
#
# Status returns:
#    0:  success
#    1:  initialization error
#
# Notes:
#    1) The complete list of header and implemention files for a package given
#       in full form may blow the environment in some operating systems and
#       the brief form should therefore be used.
#
#    2) depend is designed for parallel execution on any number of machines
#       using a "pull-queue" mechanism.
#
# Original: 1993/01/25 by Mark Calabretta, ATNF
# $Id$
#=============================================================================
# Check that CASAPATH is defined.
  if [ "$CASAPATH" = "" ] ; then
     echo "depend: CASAPATH is undefined, abort!" 1>&2
     exit 1
  fi

# Code areas.
  AIPSROOT=`echo $CASAPATH | awk '{ print $1 }'`
  AIPSCODE=$AIPSROOT/code
  CODEINCD=$AIPSCODE/include

# Parse command input.
  ELEMENTS=""
  HFILES=""

  while [ "$#" -gt 0 ]
  do
     case $1 in
        -p*)
           case $1 in
              -p)
                 shift
                 PACKAGE="$1"
                 ;;
              *)
                 PACKAGE=`echo $1 | sed -e 's/^-p//'`
                 ;;
           esac
           ;;
        *.cc)
           ELEMENT=`basename $1 .cc`
           ELEMENTS="$ELEMENTS $ELEMENT"
           ;;
        *.h)
           HFILE=`echo $1 | sed -e "s#^$AIPSCODE/##" \
                                -e 's#include/##' \
                                -e 's#implement/##'`
           HFILES="$HFILES $HFILE"
           ;;
     esac

     [ "$2" = "" ] && break

     shift
  done

# Check that the package is valid.
  case $PACKAGE in
  "")
     exec 1>&2
     echo 'Usage: depend -p package[-module] [files...]'
     echo '       ...where "package" is the name of an AIPS++ package such as'
     echo '       ..."aips", "synthesis", etc., and "module" is a recognized'
     echo '       ...software module.'
     exit 1
     ;;
  *-*)
     PCKGIMPD=$AIPSCODE/`echo $PACKAGE | sed -e 's#-#/implement/#' -e 's#-#/#g'`
     if [ ! -d "$PCKGIMPD" ]
     then
        case $PACKAGE in
	   *-tools)
	      PCKGIMPD=$AIPSCODE/`echo $PACKAGE | sed -e 's#-#/#g'`
	      ;;
	   *-idl)
	      PCKGIMPD=$AIPSCODE/`echo $PACKAGE | sed -e 's#-#/#g'`
	      ;;
	   *-xml)
	      PCKGIMPD=$AIPSCODE/`echo $PACKAGE | sed -e 's#-#/#g'`
	      ;;
	   *)
	      echo "depend: $PACKAGE is not a recognized AIPS++ package-module" \
	            "combination." 1>&2
	      exit 1
	      ;;
	esac
     fi

     case $PACKAGE in
     *-tmplinst)
        PCKGMAKD=$PCKGIMPD/..
        ;;
     *)
        PCKGMAKD=$PCKGIMPD
        ;;
     esac
     ;;
  *)
     PCKGIMPD=$AIPSCODE/$PACKAGE/implement
     if [ ! -d "$PCKGIMPD" ]
     then
        echo "depend: $PACKAGE is not a recognized AIPS++ package." 1>&2
        exit 1
     fi
     ;;
  esac


# Default file creation mask.
  umask 002

# Get the system areas.
  AIPSARCH=`echo $CASAPATH | awk '{ print $1 "/" $2 }'`
  ARCHAUXD=$AIPSARCH/aux
  AUXPCKGD=$ARCHAUXD/$PACKAGE

# Dependency files
  DPNDLIST=$ARCHAUXD/$PACKAGE.list
  DPNDTIME=$ARCHAUXD/$PACKAGE.time

# The directory may already have been created by another invokation.
  [ -d "$ARCHAUXD" ] || mkdir $ARCHAUXD
  [ -d "$AUXPCKGD" ] || mkdir $AUXPCKGD
  cd $AUXPCKGD

# Construct an identifier string.
  HOST=`echo $CASAPATH | awk '{ print $4 }'`
  JOBIDENT=$USER@$HOST:$$

# Load makedefs variables into the environment if necessary.
  if [ "$CPP" = "" -o "$CPPOPTx" = "" -o "$AIPSINCLx" = "" ]
  then
     eval `gmake -C $PCKGMAKD NODEP=1 VARS="CPP CPPOPTx AIPSINCLx" eval_vars`
  fi


# Delete timestamp files older than a day (just in case).
  find _time.* -mtime +0 -exec rm -f {} \; 2> /dev/null

# Create the timestamp file; every invokation of 'depend' must have one since
# each MUST delete one when it exits, whether naturally or prematurely.
  trap 'cd $AUXPCKGD ; rm -f $AUXPCKGD/*.$JOBIDENT' 0
  trap 'exec 1>&2 ; \
        echo "" ; \
        echo "Cleaning up..." ; \ 
        exit 1' 1 2 3 15

  set `echo _time.*`
  if [ "$1" = "_time.*" ]
  then
#    We're first, create the timestamp file.
     touch _time.$JOBIDENT

#    Just in case an old lock file was left behind.
     rm -f _lock

#    Delete any class dependency files older than the timestamp.
     find . ! -name _time.$JOBIDENT ! -newer _time.$JOBIDENT \
        -exec rm -f {} \; 2> /dev/null

#    Copy the old dependency list.
     if [ -f "$DPNDLIST" ]
     then
#       Use the old one.
        cp $DPNDLIST _list
     else
#       Start from scratch.
        touch _list
     fi

#    Let everyone know what we're up to.
     echo "depend: Generating dependencies for $PACKAGE..."
  else
#    Another invokation must be running, link to the first (and only!).
     [ -f _lock ] || ln $1 _time.$JOBIDENT
  fi


# Add classes affected by changed header files.
  for HFILE in $HFILES
  do
#    Find all class implementation files which include this header.
     CHFILES="`grep $HFILE _list | \
                  sed -e 's/^\${AIPSLIBS:%=%(\(.*\)\.o)} .*/\1/'`"

#    Remove duplicate entries.
     ELEMENTS="`for ELEMENT in $ELEMENTS $CHFILES
              do
                 echo $ELEMENT
              done | sort -u`"
  done


# Process each class implementation file.
  for ELEMENT in $ELEMENTS
  do
#    If at any time a lock file appears then we're finished.
     if [ -f _lock ]
     then
#       We're done.
        rm -f _time.$JOBIDENT

        echo "Waiting for `sed -n 1p _lock` to update the" \
             "dependency list..."
        cd $ARCHAUXD

#       Wait for the directory to disappear.
        while [ -d "$AUXPCKGD" ]
        do
           sleep 10
        done

        exit 0
     fi

#    If the dependency list disappears then exit immediately.
     [ -f _list ] || exit 0

#    Maybe it's already been done or is being done by a parallel process.
     [ "`echo $ELEMENT*`" = "$ELEMENT*" ] || continue

#    Grab it!
     touch $ELEMENT.$JOBIDENT

     if [ -f "$PCKGIMPD/$ELEMENT.cc" ]
     then
#       Now actually produce the dependency list.
        #echo "	$ELEMENT.cc"
        TARGET='${AIPSLIBS:%=%('$ELEMENT'.o)} : $(CODEINCD)/'

#       Filter out 'lex' and 'bison' includes.
        grep -v '^[ 	]*#include[ 	]*["<].*\.[ly]cc[">]' \
           $PCKGIMPD/$ELEMENT.cc > $ELEMENT.cc

#       Apply the preprocessor.
#        $CPP $CPPOPTx $AIPSINCLx $ELEMENT.cc | sed -n \
#           -e '\%^#.*"'$CODEINCD'/.*/_[a-z]*_[u]*def\.h"%d' \
#           -e '\%^#.*"'$CODEINCD'%s#.*include/\(.*\)".*#'"$TARGET"'\1#p' | \
#           sort -u > $ELEMENT.$JOBIDENT
        $CPP -MM -MT '${AIPSLIBS:%=%('$ELEMENT'.o)}' $CPPOPTx $AIPSINCLx $ELEMENT.cc > $ELEMENT.$JOBIDENT
        #echo $CPP -MM $CPPOPTx $AIPSINCLx $ELEMENT.cc \> $ELEMENT.$JOBIDENT
        #echo $ELEMENT
	#cat $ELEMENT.$JOBIDENT
	   #echo $CPPOPTx $AIPSINCLx
        rm -f $ELEMENT.cc
     else
#       A modified .h file has signalled a deleted .cc file.
        echo "Deleting dependencies for $ELEMENT.cc"
     fi

#    Release it.
     if [ ! -f "$ELEMENT" ]
     then
        mv -f $ELEMENT.$JOBIDENT $ELEMENT
     else
#       Someone's beaten us to it!
        rm -f $ELEMENT.$JOBIDENT
     fi
  done


# Defer to the NFS server of the aux directory.
  FILESYSTEM=`df $AUXPCKGD | sed -n -e '2s/[ 	]*.*//p'`
  case "$FILESYSTEM" in
  *:/*)
#     We're a client; is the server in the race?
      SERVER=`echo $FILESYSTEM | sed -e 's/:.*//'`
      if [ -f $AUXPCKGD/_time.*@$SERVER:[0-9]* ]
      then
         echo "Waiting 60 seconds for $SERVER to catch up..."
         sleep 60
      fi
      ;;
  esac

# Append our ident to the lock file, only one can be first (so you'd think)!
  echo "$JOBIDENT" >> _lock

# Update the dependency list.
  if [ "`sed -n 1p _lock`" = "$JOBIDENT" ]
  then
#    We're the first to finish!
     echo "Updating the dependency list ($JOBIDENT)..."
  else
#    We're done.
     rm -f _time.$JOBIDENT

     echo "Waiting for `sed -n 1p _lock` to update the" \
          "dependency list..."
     cd $ARCHAUXD

#    Wait for the directory to disappear.
     while [ -d "$AUXPCKGD" ]
     do
        sleep 10
     done

     exit 0
  fi

# It's now our responsibility to clean up, come what may.
  trap 'cd $ARCHAUXD ; rm -rf $AUXPCKGD' 0

# Wait ever patiently for all other invokations to finish their last job.
  for i in 5 10 15 20 25 30 35 40
  do
     JOBS=`echo _time.* | sed -e "s/_time\.$JOBIDENT//" -e 's/_time\.//g'`
     [ "$JOBS" = "" ] && break
     echo Waiting for $JOBS
     sleep $i
  done

# Add the dependencies for each class file into the list.
  for ELEMENT in $ELEMENTS
  do
     TARGET='${AIPSLIBS:%=%('$ELEMENT'.o)} : $(CODEINCD)/'

     if [ ! -f "$ELEMENT" ]
     then
#       Mop up any remaining jobs - we now have complete control.
        if [ -f "$PCKGIMPD/$ELEMENT.cc" ]
        then
           echo "	$ELEMENT.cc"

#          Filter out 'lex' and 'bison' includes.
           grep -v '^[ 	]*#include[ 	]*["<].*\.[ly]C[">]' \
              $PCKGIMPD/$ELEMENT.cc > $ELEMENT.cc

#          Apply the preprocessor.
#           $CPP $CPPOPTx $AIPSINCLx $ELEMENT.cc | sed -n \
#              -e '\%^#.*/_[a-z][a-z]*_u*def\.h"%d' \
#              -e '\%^#.*"'$CODEINCD'%s#.*include/\(.*\)".*#'"$TARGET"'\1#p' | \
#              sort -u > $ELEMENT
           $CPP -MM -MT '${AIPSLIBS:%=%('$ELEMENT'.o)}' $CPPOPTx $AIPSINCLx $ELEMENT.cc >$ELEMENT
           echo $CPP -MM $CPPOPTx $AIPSINCLx $ELEMENT.cc \>$ELEMENT
	   #cat $ELEMENT
	   #echo $CPPOPTx $AIPSINCLx
           rm -f $ELEMENT.cc
        else
#          A modified .h file has signalled a deleted .cc file.
           echo "Deleting dependencies for $ELEMENT.cc"
           touch $ELEMENT
        fi
     fi

     sed -e "\#$TARGET#d" _list | cat - $ELEMENT > _new
     mv -f _new _list
  done

# Sort and install the updated list.
#  sort -u _list > $DPNDLIST
  mv _list $DPNDLIST
  mv -f _time.$JOBIDENT $DPNDTIME
  echo "Dependency list updated ($JOBIDENT)."

# Clean up explicitly, this will kill any deliquent invokations.
  cd $ARCHAUXD
  rm -rf $AUXPCKGD


  exit 0
