#!/bin/bash
FILES="$*"
#HEADERS=`for DIR in subversion/include apr/include apr-util/include; do (cd $DIR && echo *.h); done`
HEADERS=`for DIR in subversion/include; do (cd $DIR && echo *.h); done`
# . 
# /usr/local/include/neon 
# ~/src/subversion/neon/src 
# ~/src/subversion/subversion/include 
# ~/build/subversion/apr/include 
# ~/src/subversion/apr/include   
# ~/build/subversion/apr-util/include 
# ~/src/subversion/apr-util/include 

if [ "$FILES" = "" ]; then
  echo "Find C files that don't use headers that they include."
  echo "usage: includes FILES"
  exit 1
fi

for HEADER in $HEADERS; do
  # HEADER is something like "svn_path.h"
  PREFIX="${HEADER%\.h}_[a-z]"
  if [ "$HEADER" = "svn_sorts.h" ]; then
    PREFIX="svn_sort_[a-z]"
  fi

  INCLUDE_RE="^ *# *include *.$HEADER."

  # Do all the symbols declared in that header (excluding #defines and members)
  # have the corresponding prefix?
#  if ! grep "/$HEADER	.*	[^dm]$" tags | grep -v --silent "^$PREFIX"; then
    #echo "'$HEADER'	uses the sole prefix '$PREFIX'"

    # Do any files include that header but not use it?
#    grep -L "\<${PREFIX}" $FILES | xargs grep -nH "$INCLUDE_RE"

    # Do any files use that header but not (directly) include it?
#    grep -L "$INCLUDE_RE" $FILES | xargs grep -H --max-count=2 "\<${PREFIX}"

    # An alternative method for finding the inconsistencies
    #FILES_INCLUDING=`grep -l "$INCLUDE_RE" $FILES`
    #FILES_USING=`grep -l "\<${PREFIX}" $FILES`
    #FILES_DIFFERING=`{ echo "$FILES_INCLUDING"; echo "$FILES_USING"; } | sort | uniq --unique`
    #for FILE in $FILES_DIFFERING; do
    #  grep -H "$HEADER" "$FILE" || echo "$FILE: does not include '$HEADER'"
    #  grep -H --max-count=3 "$PREFIX" "$FILE"
    #done
#  fi

  # Check all of the symbols listed for this header in the "tags" file.
  SYMBOLS=`grep "/$HEADER	.*	[^m]\(	.*\)*$" tags | cut -f 1`
  #echo
  #echo "$HEADER: symbols:" $SYMBOLS
  for FILE in $FILES; do
    INCLUDED=`grep -l "$INCLUDE_RE" "$FILE"`
    USED=`grep -l -F "$SYMBOLS" "$FILE"`
    if [ "$INCLUDED" ] && [ -z "$USED" ]; then
      #echo "$HEADER is included but not used by $FILE"
      grep -H "$INCLUDE_RE" "$FILE"
    elif [ -z "$INCLUDED" ] && [ "$USED" ]; then
      echo "$FILE:#MISSING \"$HEADER\""
      grep -H --max-count=2 -F "$SYMBOLS" "$FILE"
    fi
  done
done
