#!/bin/sh

dest=common.h;
src=build;
thresh=40;
root=`cd \`dirname "$0"\`/..; pwd`/

usage="\
$0 [-d|--dest <output_file>] [-b|--builddir <builddir>] \n \
   [-t|--threshold <threshold_value>] [-r|--root <tekkotsu_root>] \n \
   [-f|--force <file>] [-p|--force-pattern <regexp>] \n \
   \n \
   If unspecified, destination is $dest and builddir is $src, both \n \
   relative to the current directory (`pwd`). \n \
   \n \
   Threshold defaults to $thresh.\n \
   \n \
   force and force-pattern allow you to explicitly add files to the \n \
   list, even if  they wouldn't otherwise break the threshold.  You can \n \
   use --force multiple times to specify several files, but you can only \n \
   specify one regexp pattern (the last one specified will be used -- use \n \
   the 'or' token '|' to get around this) \n \
   \n \
   root defaults to '$root', and will be removed from \n \
   each of the file names for portability. \n \
   \n";

while [ $# -gt 0 ] ; do
    case "$1" in
	-r|--root) root="$2"; shift; shift ;;
	-d|--dest) dest="$2"; shift; shift ;;
	-b|--builddir) src="$2"; shift; shift ;;
	-t|--threshold) thresh=$2; shift; shift ;;
	-f|--force) forced="$forced $2"; shift; shift ;;
	-p|--force-pattern) pattern="$2"; shift; shift;;
	*) printf "$usage"; exit 2 ;;
    esac;
done;

rm -f $dest;
echo "/* This is a file lists the most depended-upon header files used by" >> "$dest"
echo " * the project.  It is automatically generated by tools/genCommonHeader." >> "$dest"
echo " * When compiling for PLATFORM_LOCAL, this header will be precompiled. " >> "$dest"
echo " * It was created at `date` and checked into " >> "$dest"
echo " * CVS at \$Date: 2005/06/01 05:48:08 $ */" >> "$dest"
echo "" >> "$dest"

echo "#ifdef __cplusplus //lets us blindly apply to C files as well" >> "$dest"
echo "" >> "$dest"

for plat in PLATFORM_LOCAL PLATFORM_APERIOS ; do

    if [ ! -d "$src/$plat" ] ; then
	echo Warning: "$src/$plat" not found or not a directory;
	continue;
    fi;
    echo "#ifdef $plat" >> "$dest"
    for modelbuild in "$src/$plat/TGT"* ; do
	echo "Processing $modelbuild...";
	model=`echo "$modelbuild" | sed "s@$src/$plat/@@"`;
	echo "#ifdef $model" >> "$dest";
	( find "$modelbuild" -name "*.d" | xargs sed -n 's/\(.*\.h\):$/\1/p' ) | sed "s@^$root@@" | sort | uniq -c | sort -nr | \
	while read n file ; do
	    if [ $n -ge $thresh ] ; then
		echo "#include \"$file\" //$n" >> "$dest" ;
	    elif echo "$file" | grep -q "$pattern" ; then
		echo "#include \"$file\" //forced (pattern match)" >> "$dest" ;
	    fi;
	done;
	for f in $forced ; do
	    echo "#include \"$f\" //forced" >> "$dest" ;
	done;
	echo "#endif //$model" >> "$dest";
    done;
    echo "#endif //$plat" >> "$dest"
    echo "" >> "$dest"
done;
echo "#endif //cplusplus" >> "$dest"
