#!/bin/sh

# $Id: checkIncOrder,v 1.5 1995/08/24 09:10:35 svein Exp $
# Author: Svein Bøe, 1994

usage () {
  echo "usage: $prog [-h] [-n] [<files>]"
  echo "  <files>  : C-files and header-files, default: All in 'cwd'."
  echo "  -h       : Print this text."
  echo "  -n       : Do not change any files, only tell what should be done."
  echo ""
  echo "Purpose:"
  echo "Check the order of the include directives in .c or .h-files."
  echo "Make sure that '#include <xite/includes.h>' is included before"
  echo "any of '#include XITE_*', '#include <xite/*.h>' or #include <X11/*>."
  echo ""
  echo "Multiple inclusions of same header are removed, this may not be"
  echo "what you want (in conditional compilation)."

  exit 1
}

prog=`basename $0`; files=""; help=0; dont=0;
scriptDir=`expr $0 : "\(.*\)$prog"`
while [ $# -gt 0 ]; do
  case $1 in
    -h|-help)  help=1; usage;;
    -n)        dont=1;
	       shift;;
    *)         if [ -z "$files" ]; then
	         files=$1
	       else
		 files="$files $1"
	       fi
	       shift;;
  esac
done

if [ -z "$files" ]; then
  files=`ls *.c *.h 2>/dev/null`
fi

if [ -z "$files" ]; then
  echo "No such files." 1>&2
  usage
fi

for file in $files; do
  grep '^#include *XITE_' $file > /dev/null || \
    grep '^#include *<xite\/.\{1,\}\.h>' $file > /dev/null || \
      grep '^#include *<X11\/.\{1,\}>' $file > /dev/null || continue

  if [ "$dont" -eq 1 ]; then
    echo "file: $file"
    gawk -f ${scriptDir}checkIncOrder.awk dont=$dont $file > /dev/null
  else
    gawk -f ${scriptDir}checkIncOrder.awk dont=$dont $file > $file.awk
  fi

  if [ $? -ne 0 ]; then
    echo "$prog: Error in gawk script. Exiting."
    rm $file.awk
    exit 1
  fi

  if [ "$dont" -eq 1 ]; then
    continue
  fi

  if [ -z "`diff "$file" "$file.awk"`" ]; then
    rm $file.awk
    continue
  fi


  mv $file.awk $file
done
