#!/bin/sh

# We don't do that here
exec 2> /dev/null

# Initialization inspired by dlog_test.in, TODO: unify somehow
if [ $# -ne 1 ]; then
	echo "usage: $0 pipe|logger"
	exit 1
fi

if [ "$1" = "pipe" ]; then
	type="pipe"
elif [ "$1" = "logger" ]; then
	type="logger"

	# Make sure the newly launched daemon ignores old logs
	touch /run/dlog/first_time
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

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

LOGGER=-1
TEST=-1
RUNTIME_FILTERS_DIR="/tmp/dlog-filters/"
WRITER_DIR="/tmp/dlog-writers/"

cleanup() {
	[ $LOGGER -ne -1 ] && kill $LOGGER > /dev/null 2>&1
	[ $TEST -ne -1 ] && kill $TEST > /dev/null 2>&1
	[ -d $RUNTIME_FILTERS_DIR ] && rm -rf $RUNTIME_FILTERS_DIR
	[ -d $WRITER_DIR ] && rm -rf $WRITER_DIR
}
trap cleanup 0

mkdir -p "$RUNTIME_FILTERS_DIR"
mkdir -p "$WRITER_DIR"

dlog_logger &
LOGGER=$!
sleep 1
(while :; do dlogsend -c 1000 -b main -t DLOG_CPU_TEST1 hi; sleep 0.1; done) &
TEST=$!
sleep 10
ps --no-headers --quick-pid $LOGGER --format %cpu
