#!/bin/sh

# stuff for tracking test case counts
FAILS=0
OKS=0
TOTAL=0
LOG_DETAILS=

#relevant pids default vals
UTIL_PID=-1
MT_TEST=-1
LOGGER=-1

TEST_DYNAMIC_FILTERS="true"
TESTDIR=/var/lib/dlog-tests

extract_timestamp() {
	local ts=0
	case "$1" in
		"threadtime")
			time=`echo $2 | awk -F '[ +]' '{print $2}'`
			ts=`date +%s%N -d $time`
		;;
		"long")
			time=`echo $2 | awk -F '[ +.]' '{print $3}'`
			ms=`echo $2 | awk -F '[ +.]' '{print $4}'`
			sec=`date +%s%N -d $time`
			ns=$((10#$ms * 1000000))
			ts=$(($sec + $ns))
		;;
		"rwtime")
			time=`echo $2 | awk -F '[ +.]' '{print $2}'`
			ts=`date +%s%N -d $time`
		;;
		"recv_realtime")
			time=`echo $2 | awk -F '[ +.]' '{print $2}'`
			ts=`date +%s%N -d $time`
		;;
		"time")
			time=`echo $2 | awk -F '[ +.]' '{print $2}'`
			ts=`date +%s%N -d $time`
		;;
		"kerneltime")
			ts=`echo $2 | awk -F '[ +]' '{print $1}' | sed -e 's/\.//g'`
		;;
	esac
	echo "$ts"
}

cleanup() {
	[ $UTIL_PID -ne -1 ] && kill $UTIL_PID > /dev/null 2>&1
	[ $MT_TEST  -ne -1 ] && kill $MT_TEST  > /dev/null 2>&1
	[ $LOGGER   -ne -1 ] && kill $LOGGER   > /dev/null 2>&1
	[ -d $TESTDIR ] && rm -rf $TESTDIR/*
	[ -d $RUNTIME_FILTERS_DIR ] && rm -rf $RUNTIME_FILTERS_DIR
}

trap cleanup 0

check_daemon() {
	local ret=1
	if [ $LOGGER -ne -1 ] && [ -z "$(ps -o pid= -p $LOGGER)" ]; then
		ret=0
	fi
	return $ret
}

fail() {
	check_daemon
	[ $? -eq 0 ] && daemon_status="[logger daemon not running]"

	FAILS=$(($FAILS + 1))
	TOTAL=$(($TOTAL + 1))
	printf "[%02d] FAILED: %s %s\n" $TOTAL "$LOG_DETAILS" "$daemon_status"
	LOG_DETAILS=
}

ok() {
	check_daemon
	[ $? -eq 0 ] && daemon_status="[logger daemon not running]"

	OKS=$(($OKS + 1))
	TOTAL=$(($TOTAL + 1))
	printf "[%02d] PASSED: %s %s\n" $TOTAL "$LOG_DETAILS" "$daemon_status"
	LOG_DETAILS=
}

# supress stderr messages from subcommands
exec 2> /dev/null

if [ $# -ne 1 ]; then
	echo "usage: $0 pipe|logger"
	exit 1
fi

if [ "$1" == "pipe" ]; then
	type="pipe"
elif [ "$1" == "logger" ]; then
	type="logger"
else
	echo "usage: $0 pipe|logger"
	exit 1
fi

NEEDS_TO_QUIT=0
capsh --print | grep Current | grep cap_syslog > /dev/null || { echo "*** ERROR: cap_syslog missing"; NEEDS_TO_QUIT=1; }
mount | grep ' / ' | grep rw > /dev/null || { echo "*** ERROR: root not mounted read-write"; NEEDS_TO_QUIT=1; }
[[ $NEEDS_TO_QUIT -eq 0 ]] || exit 1

if [ -z "$DLOG_CONFIG_PATH" ]; then
	ORIGINAL_CONFIG_PATH="/etc/dlog.conf"
else
	ORIGINAL_CONFIG_PATH="$DLOG_CONFIG_PATH"
fi

export DLOG_CONFIG_PATH="/usr/share/dlog-$type.conf.test"
PATH=$PATH:/usr/libexec/libdlog/

#create dir for runtime filters
RUNTIME_FILTERS_DIR="/tmp/dlog-filters/"
mkdir -p "$RUNTIME_FILTERS_DIR"

# Start the daemon
if [ $type == "pipe" ]; then
	dlog_logger -b 99 -t 0 &
	LOGGER=$!
	sleep 1
fi

if [ "$TEST_DYNAMIC_FILTERS" == "true" ]; then
	dlogctl -c
	dlogctl --enable
	dlogutil -c -b radio -b system -b main
	LOG_DETAILS="dlogctl --disable (no args)"
	dlogctl --disable
	[ `dlogctl -g | grep ENABLED | wc -l` -eq 0 ] && ok || fail
	LOG_DETAILS="testing if filters were applied"
	dlogsend -b system -t TEST test
	dlogsend -b main -t TEST test
	dlogsend -b radio -t TEST test
	[ `dlogutil -d -b radio -b system -b main | wc -l` -eq 0 ] && ok || fail

	LOG_DETAILS="dlogctl --enable (no args)"
	dlogctl --enable
	[ `dlogctl -g | grep DISABLED | wc -l` -eq 0 ] && ok || fail
	LOG_DETAILS="testing if filters were applied"
	dlogutil -c -b radio -b system -b main
	dlogsend -b system -t TEST test
	dlogsend -b main -t TEST test
	dlogsend -b radio -t TEST test
	[ `dlogutil -d -b radio -b system -b main | wc -l` -eq 3 ] && ok || fail

	LOG_DETAILS="dlogctl --disable (1 arg)"
	dlogctl --disable -b system
	[ `dlogctl -g | grep DISABLED | grep system | wc -l` -eq 1 ] &&
	[ `dlogctl -g | grep DISABLED               | wc -l` -eq 1 ] && ok || fail
	LOG_DETAILS="testing if filters were applied"
	dlogutil -c -b radio -b system -b main
	dlogsend -b system -t TEST test
	dlogsend -b main -t TEST test
	dlogsend -b radio -t TEST test
	[ `dlogutil -d -b radio -b system -b main | wc -l` -eq 2 ] && ok || fail

	LOG_DETAILS="dlogctl --disable (multiple args)"
	dlogctl --disable -b main -b radio
	[ `dlogctl -g | grep DISABLED | grep -v system | wc -l` -eq 2 ] &&
	[ `dlogctl -g | grep DISABLED | grep     radio | wc -l` -eq 1 ] &&
	[ `dlogctl -g | grep DISABLED | grep      main | wc -l` -eq 1 ] && ok || fail
	LOG_DETAILS="testing if filters were applied"
	dlogutil -c -b radio -b system -b main
	dlogsend -b system -t TEST test
	dlogsend -b main -t TEST test
	dlogsend -b radio -t TEST test
	[ `dlogutil -d -b radio -b system -b main | wc -l` -eq 0 ] && ok || fail

	LOG_DETAILS="dlogctl --enable (multiple args)"
	dlogctl --enable -b radio -b system
	[ `dlogctl -g | grep DISABLED               | wc -l` -eq 1 ] &&
	[ `dlogctl -g | grep DISABLED | grep   main | wc -l` -eq 1 ] &&
	[ `dlogctl -g | grep  ENABLED | grep system | wc -l` -eq 1 ] &&
	[ `dlogctl -g | grep  ENABLED | grep  radio | wc -l` -eq 1 ] && ok || fail
	LOG_DETAILS="testing if filters were applied"
	dlogutil -c -b radio -b system -b main
	dlogsend -b system -t TEST test
	dlogsend -b main -t TEST test
	dlogsend -b radio -t TEST test
	[ `dlogutil -d -b radio -b system -b main | wc -l` -eq 2 ] && ok || fail

	LOG_DETAILS="dlogctl --enable (1 arg)"
	dlogctl --enable -b main
	[ `dlogctl -g | grep DISABLED | wc -l` -eq 0 ] && ok || fail
	LOG_DETAILS="testing if filters were applied"
	dlogutil -c -b radio -b system -b main
	dlogsend -b system -t TEST test
	dlogsend -b main -t TEST test
	dlogsend -b radio -t TEST test
	[ `dlogutil -d -b radio -b system -b main | wc -l` -eq 3 ] && ok || fail

	LOG_DETAILS="dlogctl -s allow"
	dlogutil -c -b radio -b system -b main
	dlogctl -c
	dlogctl -s deny
	dlogctl -t TEST_TAG -s allow
	dlogsend -b main -t TEST_TAG test
	dlogsend -b main -t TEST test
	[ `dlogutil -d -b main | wc -l` -eq 1 ] && ok || fail

	LOG_DETAILS="dlogctl -s [N]"
	dlogutil -c -b radio -b system -b main
	dlogctl -c
	dlogctl -s deny
	dlogctl -t TEST_TAG -s 3
	dlogsend -b main -c 10 -t TEST_TAG test
	dlogsend -b main -c 10 -t TEST test
	[ `dlogutil -d -b main | wc -l` -eq 4 ] && ok || fail

	LOG_DETAILS="testing invalid parameters for dlogctl (1/13)"
	dlogctl -s invalid &> /dev/null && fail || ok

	LOG_DETAILS="testing invalid parameters for dlogctl (2/13)"
	dlogctl -p X -g &> /dev/null && fail || ok

	LOG_DETAILS="testing invalid parameters for dlogctl (3/13)"
	dlogctl -b invalid --disable &> /dev/null && fail || ok

	LOG_DETAILS="testing invalid parameters for dlogctl (4/13)"
	dlogctl -s allow -g -t xyz -p E &> /dev/null && fail || ok

	LOG_DETAILS="testing invalid parameters for dlogctl (5/13)"
	dlogctl -s allow -c &> /dev/null && fail || ok

	LOG_DETAILS="testing invalid parameters for dlogctl (6/13)"
	dlogctl -c -g -t xyz -p E &> /dev/null && fail || ok

	# -s out of range
	LOG_DETAILS="testing invalid parameters for dlogctl (7/13)"
	dlogctl -s -10 &> /dev/null && fail || ok

	LOG_DETAILS="testing invalid parameters for dlogctl (8/13)"
	dlogctl -s 999999 &> /dev/null && fail || ok

	# -s correctness
	LOG_DETAILS="testing invalid parameters for dlogctl (9/13)"
	dlogctl -s 100 && ok || fail

	LOG_DETAILS="testing invalid parameters for dlogctl (10/13)"
	[ `cat $RUNTIME_FILTERS_DIR/FILTERS | grep -E 'limiter\|\*\|\*=100' | wc -l` -eq 1 ] && ok || fail

	# -g correctness
	LOG_DETAILS="testing invalid parameters for dlogctl (11/13)"
	[ `dlogctl -g | grep '*:*' | grep 100 | wc -l` -eq 1 ] && ok || fail

	# -c correctness
	LOG_DETAILS="testing invalid parameters for dlogctl (12/13)"
	dlogctl -c -t '*' -p '*' && ok || fail

	LOG_DETAILS="testing invalid parameters for dlogctl (13/13)"
	[ `cat $RUNTIME_FILTERS_DIR/FILTERS | grep -E 'limiter\|\*\|\*=100' | wc -l` -eq 0 ] && ok || fail
	dlogctl -c
fi

# put 100 log entries in the "main" buffer
dlogutil -c
test_libdlog 100
sleep 1


LOG_DETAILS="testing if dlogutil -d exits with success after printing logs"
dlogutil -d &> /dev/null && ok || fail

LOG_DETAILS="testing if -t argument is parsed properly"
dlogutil -t dummy &> /dev/null && fail || ok

LOG_DETAILS="testing if -u argument is parsed properly"
dlogutil -du dummy &> /dev/null && fail || ok

LOG_DETAILS="testing if limiting printed log entries to less than exists in the buffer returns proper value"
[ $(dlogutil -b main -t  20 | wc -l) -eq  20 ] && ok || fail # less logs than currently in buffer

LOG_DETAILS="testing if limiting printed log entries to more than exists in the buffer returns proper value"
[ $(dlogutil -b main -t 200 | wc -l) -eq 100 ] && ok || fail # more

LOG_DETAILS="testing if dlogutil returns exact amount of entries as there is in the buffer"
[ $(dlogutil -b main -d     | wc -l) -eq 100 ] && ok || fail # exactly

LOG_DETAILS="testing if reading from  dummy buffer returns an error as expected"
dlogutil -b nonexistent_buffer &> /dev/null && fail || ok

LOG_DETAILS="testing if reading from \"system\" buffer returns zero entries (logs are in the \"main\" buffer)"
[ $(dlogutil -d -b system | wc -l) -eq 0 ] && ok || fail

LOG_DETAILS="testing if dlogutil -c empties all buffers"
dlogutil -cb main && ok || fail

LOG_DETAILS="testing if writing entries to empty buffer and reading them returns proper amount of entries"
test_libdlog 10
[ $(dlogutil -b main -d | wc -l) -eq 10 ] && ok || fail # should be 10, not 110

LOG_DETAILS="testing if filters work (1/3)"
[ $(dlogutil -b main -d *:E | wc -l) -eq 5 ] && ok || fail # half of current logs (test_libdlog alternates between error and info log levels)

LOG_DETAILS="testing if filters work (2/3)"
[ $(dlogutil -b main -d *:W | wc -l) -eq 5 ] && ok || fail

LOG_DETAILS="testing if filters work (3/3)"
[ $(dlogutil -b main -d *:I | wc -l) -eq 10 ] && ok || fail

LOG_DETAILS="testing if exact filters work (1/3)"
[ $(dlogutil -b main -d *:=E | wc -l) -eq 5 ] && ok || fail

LOG_DETAILS="testing if exact filters work (2/3)"
[ $(dlogutil -b main -d *:=W | wc -l) -eq 0 ] && ok || fail

LOG_DETAILS="testing if exact filters work (3/3)"
[ $(dlogutil -b main -d *:=I | wc -l) -eq 5 ] && ok || fail

LOG_DETAILS="testing if adding \"silent\" filter works"
[ $(dlogutil -b main -s -d | wc -l) -eq 0 ] && ok || fail

LOG_DETAILS="testing if reading buffer size returns proper exit code"
dlogutil -gb main &> /dev/null && ok || fail

LOG_DETAILS="testing if writing all entries to single file works (-f)"
dlogutil -f $TESTDIR/dlog_test_file -d &> /dev/null && ok || fail

LOG_DETAILS="testing if the continuous mode works as expected (1/2)"
dlogutil -b main -f $TESTDIR/dlog_continuous1_file &
UTIL_PID=$!
sleep 1
kill $UTIL_PID && WAS_ALIVE=1 || WAS_ALIVE=0
UTIL_PID=-1
[[ $WAS_ALIVE -eq 1 && `wc -l < $TESTDIR/dlog_continuous1_file` -eq 10 ]] && ok || fail

LOG_DETAILS="testing if the continuous mode works as expected (2/2)"
dlogutil -b main -f $TESTDIR/dlog_continuous2_file &
UTIL_PID=$!
sleep 1
dlogsend -b main "Hi!"
sleep 1
kill $UTIL_PID && WAS_ALIVE=1 || WAS_ALIVE=0
UTIL_PID=-1
[[ $WAS_ALIVE -eq 1 && `wc -l < $TESTDIR/dlog_continuous2_file` -eq 11 ]] && ok || fail

LOG_DETAILS="testing if the monitor mode works as expected (1/2)"
dlogutil -mb main -f $TESTDIR/dlog_monitor1_file &
UTIL_PID=$!
sleep 1
kill $UTIL_PID && WAS_ALIVE=1 || WAS_ALIVE=0
UTIL_PID=-1
[[ $WAS_ALIVE -eq 1 && `wc -l < $TESTDIR/dlog_monitor1_file` -eq 0 ]] && ok || fail

LOG_DETAILS="testing if the monitor mode works as expected (2/2)"
dlogutil -mb main -f $TESTDIR/dlog_monitor2_file &
UTIL_PID=$!
sleep 1
dlogsend -b main "Hi!"
sleep 1
kill $UTIL_PID && WAS_ALIVE=1 || WAS_ALIVE=0
UTIL_PID=-1
[[ $WAS_ALIVE -eq 1 && `wc -l < $TESTDIR/dlog_monitor2_file` -eq 1 ]] && ok || fail

LOG_DETAILS="testing if writing entries to rotating files works (-r/-n)"
dlogutil -f $TESTDIR/dlog_rotating_file -r 12 -n 3 & # 3 files at 12 KB each
UTIL_PID=$!

test_libdlog 100000 &
LIBDLOGUTIL_CORRECT_PID=$!
wait $LIBDLOGUTIL_CORRECT_PID

LOG_DETAILS="testing if single file is properly created"
if [ -e $TESTDIR/dlog_test_file ]; then ok; else fail; fi

LOG_DETAILS="testing if rotating file is properly created (1/4)"
if [ -e $TESTDIR/dlog_rotating_file.1 ]; then ok; else fail; fi

LOG_DETAILS="testing if rotating file is properly created (2/4)"
if [ -e $TESTDIR/dlog_rotating_file.2 ]; then ok; else fail; fi

LOG_DETAILS="testing if rotating file is properly created (3/4)"
if [ -e $TESTDIR/dlog_rotating_file.3 ]; then ok; else fail; fi

LOG_DETAILS="testing if rotating file is properly created (4/4)"
if [ -e $TESTDIR/dlog_rotating_file.4 ]; then fail; else ok; fi

LOG_DETAILS="testing the size of log files"
if [ $(du $TESTDIR/dlog_rotating_file.3 | sed "s#$TESTDIR/dlog_rotating_file.3##g") -eq 16 ]; then ok; else fail; fi # the actual size is one sector more (so 12 -> 16) because the limit is checked after reaching it, not before

kill $UTIL_PID
UTIL_PID=-1

LOG_DETAILS="testing if libdlogutil works correctly in a simple scenario"
test_libdlogutil normal $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly without any additional settings"
test_libdlogutil defaults $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly if the callback takes some time"
test_libdlogutil timer $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with filtering on priority (1/2)"
test_libdlogutil priority $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with filtering on priority (2/2)"
test_libdlogutil priority_exact $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with log count limit"
test_libdlogutil limit $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with PID filtering"
test_libdlogutil pid $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with TID filtering"
test_libdlogutil tid $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with tag filtering (1/2)"
test_libdlogutil tag_correct $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with tag filtering (2/2)"
test_libdlogutil tag_wrong $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with prefix filtering (1/2)"
test_libdlogutil prefix_correct $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil works correctly with prefix filtering (2/2)"
test_libdlogutil prefix_wrong $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil propagates the callback return value correctly"
test_libdlogutil return $LIBDLOGUTIL_CORRECT_PID $type && ok || fail
LOG_DETAILS="testing if libdlogutil errors out correctly if used improperly"
test_libdlogutil negative $LIBDLOGUTIL_CORRECT_PID $type && ok || fail

LOG_DETAILS="testing if libdlogutil works correctly in continuous mode"
test_libdlogutil continuous $LIBDLOGUTIL_CORRECT_PID $type &
TEST_LIBDLOGUTIL_PID=$!
sleep 1
kill $TEST_LIBDLOGUTIL_PID && ok || fail
TEST_LIBDLOGUTIL_PID=-1

LOG_DETAILS="testing if libdlogutil returns the correct buffer traits"
test_libdlogutil traits $LIBDLOGUTIL_CORRECT_PID $type && ok || fail

cmd_prefix="dlogutil -d -u 0 -v"
cmd_postfix="head -n 1 "

format="process"
regex_prio="[VDIWEFS]{1}"
regex_pidtid="P[0-9[:space:]]{5,},\s{1}T[0-9[:space:]]{5,}"
regex_time="[0-9]{2}-[0-9]{2}\s{1}[0-9]{2}:[0-9]{2}:[0-9]{2}"
regex_timezone="[\+-]{1}[0-9]{4}"

for PARAM in always auto none never; do
	for PRIO in info error; do
		for OUTPUT in pipe tty; do
			if [[ "$PARAM" == "always" ]]; then
				COLOR_EXPECTED=1
			elif [[ "$PARAM" == "never" ]]; then
				COLOR_EXPECTED=0
			elif [[ "$OUTPUT" == "tty" ]]; then
				COLOR_EXPECTED=1
			else
				COLOR_EXPECTED=0
			fi

			if [[ "$PRIO" == "info" ]]; then
				REGEX="s/^I\([0-9[:space:]]{5,}\)[[:print:]]*\([[:print:]]*\)@$/1/g"
			elif [[ "$COLOR_EXPECTED" -eq 0 ]]; then
				REGEX="s/^E\([0-9[:space:]]{5,}\)[[:print:]]*\([[:print:]]*\)@$/1/g"
			else
				REGEX="s/^~\[31;1mE\([0-9[:space:]]{5,}\) ~\[0m[[:print:]]*~\[31;1m  \([[:print:]]*\)@~\[0m$/1/g"
			fi

			# -t 1 instead of | head -n 1 because the `script` command can't cope with SIGPIPE.
			COMMAND="$cmd_prefix $format -t 1"

			if [[ "$PARAM" == "none" ]]; then
				LOG_DETAILS="testing if color output is correct (implicit --color=auto/$PRIO priority/$OUTPUT output)"
			else
				COMMAND="$COMMAND --color=$PARAM"
				LOG_DETAILS="testing if color output is correct (--color=$PARAM/$PRIO priority/$OUTPUT output)"
			fi

			if [[ "$PRIO" == "info" ]]; then
				COMMAND="$COMMAND '*:=I'"
			else
				COMMAND="$COMMAND '*:=E'"
			fi

			if [[ "$OUTPUT" == "tty" ]]; then
				# This emulates a TTY. The sed call is because `script` likes to mess up the output for some reason.
				COMMAND="script -qc\"$COMMAND\" /dev/null | sed 's/\r$//'"
			fi

			# `eval` is needed since `$COMMAND` may contain `"`
			line=`eval $COMMAND | tr '\033\n' '~@'`
			[[ `echo "$line" | sed -re "$REGEX"` == "1" ]] && ok || fail
		done
	done
done
# TODO: It would be cool to also test warning messages (which have a different color),
# but this would require deeper changes to this script, which is already janky enough.

REGEX="s/^$regex_prio\([0-9[:space:]]{5,}\)[[:print:]]*\([[:print:]]*\)$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="tag"
REGEX="s/^$regex_prio\/[[:print:]]{9,}:\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="thread"
REGEX="s/^$regex_prio\($regex_pidtid\)\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="time"
REGEX="s/^$regex_time.[0-9]{3}$regex_timezone\s{1}$regex_prio\/[[:print:]]{8,}\([0-9[:space:]]{5,}\):\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="threadtime"
REGEX="s/^$regex_time.[0-9]{3}$regex_timezone\s{1}$regex_prio\/[[:print:]]{8,}\($regex_pidtid\):\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="kerneltime"
REGEX="s/^[0-9[:space:]]{1,}.[0-9]{3,}\s{1}$regex_prio\/[[:print:]]{8,}\($regex_pidtid\):\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="recv_realtime"
REGEX="s/^$regex_time.[0-9]{3}\s{1}$regex_prio\/[[:print:]]{8,}\($regex_pidtid\):\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="rwtime"
REGEX="s/^$regex_time\s{1}\[[0-9[:space:]]{3,}.[0-9[:space:]]{3,}\]\s{1}$regex_prio\/[[:print:]]{8,}\($regex_pidtid\):\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="long"
REGEX="s/^\[\s{1}$regex_time.[0-9]{3,}\s{1}$regex_prio\/[[:print:]]{8,}\s{1}$regex_pidtid\]\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | tr '\n' ' ' | sed -re $REGEX` == "1" ]] && ok || fail

format="brief"
REGEX="s/^$regex_prio\/[[:print:]]{8,}\([0-9[:space:]]{5,}\):\s{1}[[:print:]]*$/1/g"
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="json"
if [[ "$type" == "pipe" ]]; then
	REGEX="s/^\{\"priority\":\"(verbose|debug|info|warning|error|fatal|silent)\",\"pid\":[1-9][0-9]*,\"tid\":[1-9][0-9]*,\"recv_real\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$regex_timezone\",\"recv_mono\":[1-9][0-9]+\.[0-9]{9},\"sent_real\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$regex_timezone\",\"sent_mono\":[1-9][0-9]+\.[0-9]{9},\"tag\":\"[[:print:]]*\",\"msg\":\"[[:print:]]*\"\}$/1/g"
else
	REGEX="s/^\{\"priority\":\"(verbose|debug|info|warning|error|fatal|silent)\",\"pid\":[1-9][0-9]*,\"tid\":[1-9][0-9]*,\"sent_real\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$regex_timezone\",\"tag\":\"[[:print:]]*\",\"msg\":\"[[:print:]]*\"\}$/1/g"
fi
LOG_DETAILS="testing if \"$format\" print format works"
line=`$cmd_prefix $format | $cmd_postfix`
[[ `echo "$line" | sed -re $REGEX` == "1" ]] && ok || fail

format="raw"
LOG_DETAILS="testing if \"$format\" print format works"
dlogutil -c
dlogsend -b main -t DLOG_TESTSUITE rawformatTEST
line=`$cmd_prefix $format | $cmd_postfix`
[[ "$line" == "rawformatTEST" ]] && ok || fail

LOG_DETAILS="testing if KMSG works in the default format"
# We check if the command returns at least 100 logs. This seems to be a safe value.
# Feel free to change it to a reasonable yet lower value if the test happens to fail otherwise.
[[ "$(dlogutil -db kmsg | wc -l)" -gt 100 ]] && ok || fail

LOG_DETAILS="testing if KMSG works in the raw format"
last_dmesg=`dmesg | tail -n1 | sed -re "s/^\[[ 0-9]{5,}\.[0-9]{6}\] (.*)$/\1/g"`
sleep 1 # To make sure dlog has already parsed the log
dlogutil -db kmsg -v raw | grep -Fm1 "$last_dmesg" >/dev/null && ok || fail

LOG_DETAILS="testing if pid filtering works"
dlogsend -b main -t DLOG_TESTSUITE pidTEST &
sleep 1
line=`dlogutil -v raw -d --pid $!`
[[ "$line" == "pidTEST" ]] && ok || fail

LOG_DETAILS="testing if tid filtering works"
dlogsend -b main -t DLOG_TESTSUITE tidTEST &
sleep 1
line=`dlogutil -v raw -d --tid $!` #dlogsend is a single threaded app so tid is the same as pid
[[ "$line" == "tidTEST" ]] && ok || fail

mv $DLOG_CONFIG_PATH $DLOG_CONFIG_PATH.1
LOG_DETAILS="testing if secure logging works (1/2)"
grep -v enable_secure_logs $DLOG_CONFIG_PATH.1 > $DLOG_CONFIG_PATH
echo "enable_secure_logs=1" >> $DLOG_CONFIG_PATH
dlogutil -c
dlogsend -zb main -t DLOG_TESTSUITE secure &
sleep 1
dlogsend -b main -t DLOG_TESTSUITE insecure &
sleep 1
line=`dlogutil -v raw -d | head -n1`
[[ "$line" == "secure" ]] && ok || fail
LOG_DETAILS="testing if secure logging works (2/2)"
grep -v enable_secure_logs $DLOG_CONFIG_PATH.1 > $DLOG_CONFIG_PATH
echo "enable_secure_logs=0" >> $DLOG_CONFIG_PATH
dlogutil -c
dlogsend -zb main -t DLOG_TESTSUITE secure &
sleep 1
dlogsend -b main -t DLOG_TESTSUITE insecure &
sleep 1
line=`dlogutil -v raw -d | head -n1`
[[ "$line" == "insecure" ]] && ok || fail
mv $DLOG_CONFIG_PATH.1 $DLOG_CONFIG_PATH

dlogsend -b main -t DLOG_TESTSUITE_TAG0 -pI tagTEST0
dlogsend -b main -t DLOG_TESTSUITE_TAG1 -pI tagTEST1
dlogsend -b main -t DLOG_TESTSUITE_TAG2 -pF tagTEST2

LOG_DETAILS="testing if tag filtering works (1/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_TAG0' | wc -l` -eq 1 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (2/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_TAG1' | wc -l` -eq 1 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (3/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_TAG' | wc -l` -eq 0 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (4/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_TAG*' | wc -l` -eq 3 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (5/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_TAG*:I' | wc -l` -eq 3 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (6/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_TAG*:W' | wc -l` -eq 1 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (7/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_SAMSUNG' | wc -l` -eq 0 ]] && ok || fail
LOG_DETAILS="testing if tag filtering works (8/8)"
[[ `dlogutil -dv raw 'DLOG_TESTSUITE_SAMSUNG*' | wc -l` -eq 0 ]] && ok || fail

if [ "$TEST_DYNAMIC_FILTERS" == "true" ]; then
	LOG_DETAILS="testing if limiter and runtime filtering works"
	dlogutil -c -b radio
	test_filters
	[ $(dlogutil -d -b radio | wc -l) -eq 12 ] && ok || fail

	LOG_DETAILS="testing proper SMACK label for dynamic config file location"
	ORIG_FILTERS_DIR=$(cat $ORIGINAL_CONFIG_PATH | grep dynamic_config_path | awk -F "=" '{print $2}')
	[ $(ls -dZ $ORIG_FILTERS_DIR | awk -F " " '{print $1}') == "System::Shared" ] && ok || fail
fi

LOG_DETAILS="testing if libdlogutil clears the buffer correctly"
test_libdlogutil clear $LIBDLOGUTIL_CORRECT_PID $type && ok || fail

LOG_DETAILS="testing if the library works with multithreaded app"
dlogutil -f $TESTDIR/dlog_mt_test &
MT_TEST=$!
test_libdlog && ok || fail

sleep 1
kill $MT_TEST
MT_TEST=-1

dlogutil -c
SPAWN_CNT=1000

# Spawn logging scripts and wait for them to finish.
# We launch all the $SPAWN_CNT scripts in a subshell, and then use the wait command in order to
# wait for all the jobs of the subshell, which means all the logging scripts.
# Each of the logging scripts is a new subsubshell which waits a random amount of seconds and then logs
# a single message. This gets us 5 groups of logs separated by a second; there are about 200 logs in each
# group, sent about at the same time.
(
	for i in `seq 1 $SPAWN_CNT`; do
		delay=$(( (RANDOM) % 5 ))
		( sleep $delay && dlogsend -b main -t DLOG_TESTSUITE $delay ) &
	done
	wait
)

LOG_DETAILS="testing if libdlogutil sorts by the timestamp correctly"

test_libdlogutil sorting $LIBDLOGUTIL_CORRECT_PID $type && ok || fail

sort_formats="kerneltime time recv_realtime rwtime threadtime long"

for format in $sort_formats; do
	LOG_DETAILS="testing if sorting by timestamp from random sources on heavy load works ($format format)"
	prev_ts=0
	unsorted=""
	prev_line=""

	# collect data and analyze timestamps
	lines=`dlogutil -b main -d -v $format`
	while read line; do
		# filter out empty lines in "long" format
		[ -z "$line" ] && continue
		# filter out non-timestamp lines in "long" format
		if [ $format == "long" ] && [ "`echo "$line" | sed -re 's/^\[[[:print:]]*\]$/line_ok/g'`" != "line_ok" ]; then
			continue
		fi

		[ "$line" -eq "$line" ] 2>/dev/null && continue

		ts=$(extract_timestamp "$format" "$line")

		if [ "$ts" -ge "$prev_ts" ]; then
			prev_ts=$ts
		else
			printf -v unsorted '%s\n\n%s\n%s' "$unsorted" "$prev_line" "$line"
			break
		fi
		prev_line=$line
	done <<< "$lines"

	[ -z "$unsorted" ] && ok || fail
done

sleep 3

if [ $type == "pipe" ]; then

	# spawn a new daemon with limited FDs for the FD checks
	kill $LOGGER > /dev/null
	sleep 1
	ULIMIT_CURRENT=`ulimit -n`
	ulimit -n 30
	dlog_logger -b 99 -t 600 &> /dev/null &
	LOGGER=$!
	ulimit -n $ULIMIT_CURRENT

	LOG_DETAILS="checking if the daemon closes util connections without logs stored"
	run_utils
	sleep 3
	[ `ls -la /proc/$LOGGER/fd | grep fifo | wc -l` -eq 0 -a `ls -la /proc/$LOGGER/fd | grep pipe | wc -l` -eq 0 ] && ok || fail

	LOG_DETAILS="checking if the daemon closes libdlog connections"
	for i in {1..30}; do
		dlogsend -c $i -b main -p e -t FOO BAR BAZ &
	done
	dlogsend -c 99999 -b main -p e -t FOO BAR BAZ &
	sleep 0.5
	kill $!
	sleep 1.5
	[ `ls -la /proc/$LOGGER/fd | grep fifo | wc -l` -eq 0 -a `ls -la /proc/$LOGGER/fd | grep pipe | wc -l` -eq 0 ] && ok || fail

	LOG_DETAILS="checking if the daemon closes util connections with logs stored"
	run_utils
	sleep 0.5
	killall dlogutil &> /dev/null
	sleep 1.5
	[ `ls -la /proc/$LOGGER/fd | grep fifo | wc -l` -eq 0 -a `ls -la /proc/$LOGGER/fd | grep pipe | wc -l` -eq 0 ] && ok || fail
fi

# show results, clean up and return an exit code

echo "$OKS / $TOTAL tests passed"
echo "$FAILS / $TOTAL tests failed"

[[ "$FAILS" -eq 0 ]]
# THE LINE ABOVE MUST STAY THE LAST COMMAND IN THE FILE!
# This is because it is used to pass the exit code. If another command
# is executed after it, its exit code will be propagated instead.
