#!/bin/sh

# Adapted from AllegroGL: dependency file generation

# Arg 1 : $(INCLUDE_DIR) directory
# Arg 2 : $(SRC_DIR) directory

# Generates dependencies automatically

# 1. Dependencies of library sources
if test -z "$1" || test -z "$2"; then
   echo "Usage: $0 include_dir source_dir\n"

   exit 1;
fi

sources=`ls $2 | grep '\.c'`

for file in $sources; do
        src="$2/$file"
    	name=`echo $file | sed 's,^.*/,,;s,\.[^.]*$,,'`
        includes1=`grep '^[ 	]*#[ 	]*include[ 	]*[a-zA-Z0-9_][a-zA-Z0-9_]*' $src | \
          sed 's,^[ 	]*#[ 	]*include[ 	]*\([a-zA-Z0-9_]*\),\1,'`
        includes2=`grep '^[ 	]*#[ 	]*include[ 	]*".*"' $src | \
          sed 's,^[ 	]*#[ 	]*include[ 	]*"\(.*\)",\1,'`
        headers=""
	if test -n "$includes1"; then
		for header in $includes1; do
			if test -f "$1/$header"; then
				headers="$headers $1/$header"
			fi
			if test -f "$2/$header"; then
				headers="$headers $2/$header"
			fi
		done
	fi
	if test -n "$includes2"; then
		for header in $includes2; do
			if test -f "$1/$header"; then
				headers="$headers $1/$header"
			fi
			if test -f "$2/$header"; then
				headers="$headers $2/$header"
			fi
		done
	fi
	echo "\$(OBJDIR)/$name.o: $2/$file $headers"
        echo -e "\t\$(CC) \$(CFLAGS) \$(INCLUDE) -c -o \$@ \$<"
        echo
done
