#!/bin/sh

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

fail(){
	FAILS=$(($FAILS + 1))
	TOTAL=$(($TOTAL + 1))
	echo "#$TOTAL: FAILED"
}

ok(){
	OKS=$(($OKS + 1))
	TOTAL=$(($TOTAL + 1))
	echo "#$TOTAL: PASSED"
}

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

mkdir /tmp/dlog_tests

# Start the daemon, add some logs
dlog_logger -b 99 -t 0 &
LOGGER=$!
sleep 1
test_libdlog 100
sleep 1

# 1-4: test -d and -t
dlogutil -d &> /dev/null && ok || fail
if [ $(dlogutil -t  20 | wc -l) -eq  20 ]; then ok; else fail; fi # less logs than currently in buffer
if [ $(dlogutil -t 200 | wc -l) -eq 100 ]; then ok; else fail; fi # more
if [ $(dlogutil -d     | wc -l) -eq 100 ]; then ok; else fail; fi # exactly

# 5-6: test -b
dlogutil -b nonexistent_buffer &> /dev/null && fail || ok
if [ $(dlogutil -d -b apps | wc -l) -eq 0 ]; then ok; else fail; fi # the logs should be in another buffer

# 7-8: test -c
dlogutil -c && ok || fail
test_libdlog 10
if [ $(dlogutil -d | wc -l) -eq 10 ]; then ok; else fail; fi # should be 10, not 110

# 9: test filters
if [ $(dlogutil -d *:E | wc -l) -eq 5 ]; then ok; else fail; fi # half of current logs (test_libdlog alternates between error and info log levels)

# 10: test -s
if [ $(dlogutil -s -d | wc -l) -eq 0 ]; then ok; else fail; fi

# 11: test -g
dlogutil -g &> /dev/null && ok || fail

# 12-19: test -f, -r and -n
dlogutil -f /tmp/dlog_tests/dlog_test_file -d &> /dev/null && ok || fail
dlogutil -f /tmp/dlog_tests/dlog_rotating_file -r 12 -n 3 & # 3 files at 12 KB each
UTIL_PID=$!
test_libdlog 100000
sleep 1
if [ -e /tmp/dlog_tests/dlog_test_file ]; then ok; else fail; fi
if [ -e /tmp/dlog_tests/dlog_rotating_file.1 ]; then ok; else fail; fi
if [ -e /tmp/dlog_tests/dlog_rotating_file.2 ]; then ok; else fail; fi
if [ -e /tmp/dlog_tests/dlog_rotating_file.3 ]; then ok; else fail; fi
if [ -e /tmp/dlog_tests/dlog_rotating_file.4 ]; then fail; else ok; fi
if [ $(du /tmp/dlog_tests/dlog_rotating_file.3 | sed 's/\t\/tmp\/dlog_tests\/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

# Test -v
# TODO

# 20: test library
dlogutil -f /tmp/dlog_tests/dlog_mt_test &
MT_TEST=$!
test_libdlog && ok || fail

# show results and clean up

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

kill $UTIL_PID
kill $MT_TEST
kill $LOGGER
rm -rf /tmp/dlog_tests
