#!/bin/sh

FAKEPAT="getuid|geteuid|getgid|getegid|setuid|seteuid|setreuid|setgid|setegid|setregid"
FAKEPAT+="|getgroups|setgroups|chown|fchown|lchown|setfsuid|setfsgid"
FAKEPAT+="|getpwnam|getpwuid|getpwnam_r|getpwuid_r|getgrgid|getgrnam|getgrnam_r|getgrgid_r"
STATPAT="stat|fstat|lstat|fstatat"
INCPAT="fakesu.h|unistd.h|pwd.h|grp.h|sys\/stat.h"

PAT="\b($FAKEPAT|$STATPAT|$INCPAT)\b"
OPT="-E"
TYPE="c*"

function syntax {
	echo "fakesu is a program to analize the contents of source files. Use it to find "
	echo "occurrances of the in libfakesu implemented uid functions. The list of currently "
	echo "supported functions in libfakesu is:"
	echo
	echo "$FAKEPAT|$STATPAT" | sed 's/[\|]/ /g;'
	echo
	printf 'Usage: %s [options]\n' `basename $0`
	echo
	echo Options:
	printf -- " -i, --includes\t\t\tShow all include directives\n"
	printf -- " -t, --type\t\t\tFile type (default is *.c*)\n"
	printf -- " -m, --main\t\t\tFind all main() functions\n"
	printf -- " -l, --list\t\t\tSuppress normal output; list matching file names only\n"
	printf -- " -h, --help\t\t\tThis help text\n"
	printf -- " -S, --no-stat\t\t\tSuppress *stat() functions\n"
}

while [ "$1" ]; do
	case "$1" in
		-i|--includes)
			PAT="\b($FAKEPAT|$STATPAT|$INCPAT|include)\b"
			;;
		-t|--type)
			TYPE="$2"
			shift
			;;
		-S|--no-stat)
			PAT="\b($FAKEPAT|$INCPAT)\b"
			;;
		-m|--main)
			PAT="\bmain\("
			;;
		-l|--list)
			OPT="$OPT -l"
			;;
		-h|--help)
			syntax
			exit
			;;
		*)
			echo "$1: No such option"
			exit 1
			;;
	esac
	shift
done

find . -name "*.$TYPE" | xargs grep $OPT "$PAT"
