#! /bin/sh


# The following two are the ANSI sequences for start and end embolden
case $TERM in
vt*|ansi*|con*|xterm*|linux*|screen*)
  S=[1m
  E=[m
  ;;
*)
  S=
  E=
  ;;
esac

PW_DIR=`pwd`

if test x$UID != x; then
  TRUST="--with-trusted=0,2,$UID"
else
  TRUST="--with-trusted=0,2"
fi

echo; echo "${S}__ STARTING TEST EXTERNAL PROGRAM __${E}"; echo;
echo Working directory: $PW_DIR

MAKE=`which gmake`
if test "x$?" = x1 ; then
    MAKE="make -s"
else
    MAKE=`which gmake | sed -e "s%\([a-z:]\) .*%\1%g"` 
    if test "x$MAKE" = x; then
	MAKE="make -s"
    elif test "x$MAKE" = xno; then
	MAKE="make -s"
    else
	if test "x$MAKE" = "xwhich:"; then
		MAKE="make -s"
	else
		MAKE="gmake -s"
		gmake -v >/dev/null 2>&1 || MAKE="make -s"
	fi
    fi
fi

COMP=`which gcc`
if test "x$?" = x1 ; then
    COMP="cc"
else
    COMP=`which gcc | sed -e "s%\([a-z:]\) .*%\1%g"` 
    if test "x$COMP" = x; then
	COMP="cc"
    elif test "x$COMP" = xno; then
	COMP="cc"
    else
	if test "x$COMP" = "xwhich:"; then
		COMP="cc"
	else
		COMP="gcc"
		gcc -v >/dev/null 2>&1 || COMP="gcc"
	fi
    fi
fi
echo MAKE is $MAKE
echo COMP is $COMP
echo


testext0 ()
{
	#
	# standalone compilation
	#
	echo "${S}Building standalone agent${E}"; echo;
	#
	if test -r "Makefile"; then
		${MAKE} distclean
	fi
	#
	${TOP_SRCDIR}/configure --quiet --enable-debug --prefix=$PW_DIR --localstatedir=$PW_DIR --with-config-file=$PW_DIR/testrc_1ext --with-log-file=$PW_DIR/.samhain_log --with-pid-file=$PW_DIR/.samhain_lock --with-data-file=$PW_DIR/.samhain_file 
	#
	if test x$? = x0; then
		echo "configure completed, exit status 0"; echo;
		${MAKE}  > /dev/null
		echo "${MAKE} completed, exit status $?"; echo;
	else
		echo "ERROR: configure failed"; echo;
	fi

	# prepare the program
	#
	cat test/test_ext.c.in | sed -e "s%MYPWDIR%$PW_DIR/test_ext.res%g" > test_ext.c
	
	${COMP} -o test_ext test_ext.c 
	if test "x$?" != x0; then
	    echo "FAIL: ${COMP} -o test_ext test_ext.c"
	    exit 1
	fi
	chmod +rx  $PW_DIR/test_ext

	# compute checksum and fix config file
	#
	cp test/testrc_1ext.in testrc_1ext
	CHKSUM=`./samhain -H $PW_DIR/test_ext |  awk '{ print $2$3$4$5$6$7}'`
	echo "OpenCommand=$PW_DIR/test_ext" >> testrc_1ext
	echo "SetType=log"                  >> testrc_1ext
	echo "SetChecksum=$CHKSUM"          >> testrc_1ext
	echo "SetFilterOr=ALERT"            >> testrc_1ext

	rm -f $PW_DIR/test_ext.res
	rm -f $PW_DIR/pdbg.child
	rm -f $PW_DIR/pdbg.main
	./samhain 
	
	# The shell is too fast ...
 	sleep 1
	echo; 
	echo "${S}Logged by external C program test_ext (filtered: ALERT only):${E}"; 
	echo;
	cat $PW_DIR/test_ext.res
	echo;

	rm -f $PW_DIR/.samhain_file
	rm -f $PW_DIR/.samhain_log
	rm -f $PW_DIR/.samhain_lock
	
}



	testext0


echo; echo "${S}__ END TEST EXTERNAL PROGRAM __${E}"; echo;

exit

