#!/bin/sh
#
# $Id: run_makedepend,v 1.3 2000/11/04 17:44:23 arodrig6 Exp $
#
# $Copyright$
#

#
# This used to be part of Makefile.depend (in the top-level
# directory), but it got to be too compilcated, and keeping the "make"
# quoting and syntax rules was just too much of a pain.  Hence, it has
# become it's own script (and so we return, full circle, to the Origin
# of LAM...).
#

#
# Note that the -o option to makedepend may only work on Solaris!
#
# UNBELIEVEABLE.  Both Solaris make and gmake have the same erroneous
# behavior.  In a list of $(SOURCEFILES), they will both prefix each
# entry with the VPATH... EXCEPT THE LAST ENTRY!  Hence, we have to
# strip the $(srcdir) from every entry (if it's there), and then put
# it back.  #$@%@#$%@#$%!!!
#
# We then have to strip out $(srcdir) from the resulting Makefile.
# <sigh>
#

srcdir="$1"
makedepend="$2"
suffix="$3"
flags="$4"
if test "$suffix" = ""; then
    suffix="lo"
fi

shift
shift
shift
shift

#
# Is this a VPATH build?
#

builddir="`pwd`"
cd "$srcdir"
real_srcdir="`pwd`"
cd "$builddir"
if test "$builddir" != "$real_srcdir"; then
    dir="`echo $srcdir | sed -e 's/\//\\\\\//g'`"
else
    dir=""
fi

#
# Snip the previous dependencies from the old Makefile
#

if test "`egrep '^# DO NOT DELETE' Makefile`" != ""; then
    ed Makefile > /dev/null <<EOF
/^# DO NOT DELETE
.,\$d
w
q
EOF
fi

#
# Start processing the file list
# Some #$%#@% shells can't handle too much in a single shell variable,
# so we process the file list 25 at a time.  #$@@#%@#$!!!
#

while test "$*" != ""; do
    files=""
    count=0
    while test "`expr $count \< 25`" = "1" -a "$1" != ""; do
	files="$files $1";
	count="`expr $count + 1`"
	shift
    done

    # If this is VPATH, cook the list to remove and re-add the $srcdir

    if test "$dir" != ""; then
	files="`echo $files | sed -e s/$dir\\\///g`"
	files="`echo $files | \
		sed -e 's/[a-zA-Z0-9_\-\.]*\.c[ \t]/'$dir'\/&/g' | \
		sed -e 's/[a-zA-Z_0-9\-\.]*\.c$/'$dir'\/&/g' | \
		sed -e 's/[a-zA-Z_0-9\-\.]*\.cc[ \t]/'$dir'\/&/g' | \
		sed -e 's/[a-zA-Z_0-9\-\.]*\.cc$/'$dir'\/&/g' | \
		sed -e 's/[a-zA-Z_0-9\-\.]*\.h/'$dir'\/&/g'`"
    fi

    echo Generating dependencies for: $files

    rm -f depfile
    touch depfile
    string="$makedepend -fdepfile -o .$suffix $flags -- -- $files"
    echo "$string"
    eval "$string"
    cat depfile >> Makefile
    rm -f depfile depfile.bak
done

#
# When we're all done, if this was VPATH, we have to strip the leading
# $srcdir out of the Makefile dependency list entries.
#

if test "$dir" != ""; then
    echo "Frobbing final Makefile..."
    sed -e 's/^'$dir'\///g' Makefile > Makefile.new
    rm -f Makefile
    mv Makefile.new Makefile
fi
