#!/bin/sh
# check.sh - do checks on a source file
# usage: check.sh [--set] topdir sourcefile

usage() {
    echo "$0: Usage: $0 [--tool|main|example] topdir srcfile" 1>&2
}

SET=unknown
case "$1" in
    --tool) SET=tool; shift;;
    --main) SET=main; shift;;
    --example) SET=example; shift;;
    -*) usage; exit 1;;
esac
if [ $# != 2 ]; then
    usage; exit 1
fi

cd "$1" || exit 1
FILE="$2"

############################################################
#
# 1. Find unapproved preprocessor symbols used in conditionals.
#

egrep -n '^(#if|#elif)' "$FILE" | tr -d '\r' | expand |\
  awk '{
	lineno=$1;
	sub(":.*", "", lineno);
	sub("^[0-9]*:", "", $1);

	directive=$1;

	if (file ~ "\\.h$" || file ~ "\\.hpp$") {
	    sym=file;
	    sub("^.*/", "", sym);
	    sym=toupper(sym);
	    gsub("\\.", "_", sym);
	    gsub("-", "_", sym);
	    if (sym == $2 && directive == "#ifndef") {
		next;
	    }
	}

	sub("//.*", "", $0);
	sub("/\\*.*\\*/", "", $0);
	sub(" *$", "", $0);

	$1 = file ":" lineno ": @";

	print;
  }' "file=$FILE" | sed '
	/@ 0$/d

	/@ __BCPLUSPLUS__$/d
	/@ __GNUC__$/d
	/@ __IBMCPP__$/d
	/@ _MSC_VER$/d
	/@ __WATCOM_CPLUSPLUS__$/d

	/@ O_BINARY$/d
    ' | (
	if [ $SET = main ]; then
	    sed '
		/@ AG_ON_AMIGA$/d
		/@ AG_ON_UNIX$/d
		/@ AG_ON_WINDOWS$/d

		/@ DUMMYGUI$/d
		/@ VACLGUI$/d

		/@ INCLUDE_LOGGING$/d
		/@ AG_EXE$/d
	    '
	elif [ $SET = example ]; then
	    sed '
		/@ __MSDOS__$/d
		/@ defined(__MSDOS__) || defined(__WINDOWS__)$/d
	    '
	else
	    cat
	fi
    ) | sed '
	s/@ /Symbol `/
	s/$/'"'"' in conditional/
  '


############################################################
#
# 2. Check for certain issues with header files.
#

awk < "$FILE" '
    {
	++lineno;
	sub("\r$", "", $0);
	gsub("\t", " ", $0);
	gsub("/\\*.*\\*/", " ", $0);
	sub(" *$", "", $0);
	sub("^ *# *", "#", $0);
    }

    function complain(msg) {
	printf "%s:%d: %s\n", file, lineno, msg;
	bad = 1;
    }

    /^#include / && $2 == "<sys/types.h>" { systypes=1; }
    /^#include / && $2 ~ "<sys/.*\\.h>" && !systypes {
	complain(sprintf("Used %s without <sys/types.h>", $2));
    }
	
    set=="main" && /^#include / && $2 == "<assert.h>" {
	complain("Used system <assert.h>");
    }

    # The tree is not ready for these measures

    #length($0) > 79 {
    #    complain("Line too long");
    #}

    #(/break;/ || /continue;/ || /return[^;]*;/) &&
    #!(/^ *break; *$/ || /^ *continue; *$/ || /^ *return[^;]*; *$/) {
    #    complain("break/continue/return not on own line");
    #}

    #{
    #    t = $0;
    #    gsub(", ", " ", t);
    #    sub(",$", "", t);
    #    if (t ~ ",") {
    #        complain("comma without following space");
    #    }
    #}

    END {
	exit(bad);
    }
' "file=$FILE" "set=$SET"

#if [ "$?" != 0 ]; then
#    BAD=1
#fi

############################################################

# done
exit 0
