#!/bin/sh

. $LKP_SRC/lib/env.sh

monitor=$1
monitor_dir=$(dirname $0)
shift

# Always use a FIFO, whose 64k buffer helps prevent write stalls on NFS dir.
fifo=$TMP/fifo-$monitor

# The same monitor already running. This could happen if the expanded default
# monitors happen to duplicate what's specified additionally by the user.
[ -p $fifo ] && exit 0
mkfifo $fifo 2>/dev/null || exit 0

if grep -q -x -F $monitor $LKP_SRC/etc/monitors_need_gzip; then
	#
	# FILE          SIZE     COMPRESS TIME
	# ====================================================================
	# trace         90M
	# trace.lzo     10M      0.10s user 0.03s system 97% cpu  0.132 total
	# trace.gz      5.0M     1.17s user 0.04s system 99% cpu  1.223 total
	# trace.bz2     4.1M    18.80s user 0.10s system 99% cpu 18.919 total
	# trace.lzma    3.1M    86.63s user 0.14s system 99% cpu 1:26.91 total
	#
	# gzip is pretty balanced.
	#

	# gzip may link to busybox which not support other name to link
	if [ -L '/bin/gzip' ]; then
		gzip='gzip'
	else
		gzip="gzip-$monitor"
	fi

	[ -L "$LKP_SRC/bin/$gzip" ] || ln -s -T /bin/gzip $LKP_SRC/bin/$gzip

	if [ "$monitor" = 'ftrace' ]; then
		# ftrace output may be too large for tmpfs
		$gzip -c < $fifo | cat	> $RESULT_ROOT/$monitor.gz &
	else
		$gzip -c < $fifo	> $TMP_RESULT_ROOT/$monitor.gz &
	fi
else
	if [ -z "$avoid_nfs" ] &&
		( [ "$monitor" = heartbeat ] || [ "$monitor" = kmsg ] ); then
		cat $fifo > $RESULT_ROOT/$monitor &
	else
		cat $fifo > $TMP_RESULT_ROOT/$monitor &
	fi
fi

echo $! >> $TMP/.pid-pipes

# Save pid to be killed when the tests complete.
# gzip/cat will auto quit when the FIFO writer is killed.
echo $$ >> $TMP/pid-bg-proc-$monitor

# Some setup scripts take time and we don't want to profile them.
$LKP_SRC/bin/event/wait 'activate-monitor'

has_cmd stdbuf &&
stdbuf='stdbuf -oL -e0'

exec $stdbuf $monitor_dir/$monitor "$@" > $fifo

