#!/bin/bash
#
# Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
#
# SPDX-License-Identifier: LGPL-2.1-only

TEST_DESC="UST tracer - Multi-session"

CURDIR=$(dirname "$0")/
TESTDIR=$CURDIR/../../..
NR_ITER=100
SESSION_NAME="multi-session"
EVENT_NAME="ust_gen_nevents:tptest"
NUM_TESTS=28

# shellcheck source=../../../utils/utils.sh
source $TESTDIR/utils/utils.sh

if [ ! -x "$CURDIR/gen-nevents" ]; then
	BAIL_OUT "No UST nevents binary detected."
fi

# MUST set TESTDIR before calling those functions

test_multi_session() {
	local out

	# BEFORE application is spawned
	for i in $(seq 0 3); do
		create_lttng_session_ok "$SESSION_NAME-$i" "$TRACE_PATH/$i"
		enable_ust_lttng_event_ok "$SESSION_NAME-$i" "$EVENT_NAME$i"
		start_lttng_tracing_ok "$SESSION_NAME-$i"
	done

	"./$CURDIR/gen-nevents" $NR_ITER &
	ok $? "Start application to generate $NR_ITER events"

	wait
	pass "Wait for events to record"

	for i in $(seq 0 3); do
		stop_lttng_tracing_ok "$SESSION_NAME-$i"
		destroy_lttng_session_ok "$SESSION_NAME-$i"
		out=$($BABELTRACE_BIN "$TRACE_PATH/$i" | grep -c "$EVENT_NAME$i")
		if [ "$out" -ne $NR_ITER ]; then
			fail "Trace validation of $SESSION_NAME-$i"
			diag "No events found."
			out=1
			break
		else
			pass "Trace validation of $SESSION_NAME-$i"
			diag "Found $out event(s) for $SESSION_NAME-$i."
			out=0
		fi
	done

	return $out
}

# MUST set TESTDIR before calling those functions

plan_tests $NUM_TESTS

print_test_banner "$TEST_DESC"

start_lttng_sessiond

TRACE_PATH=$(mktemp --tmpdir -d tmp.test_multi_session_ust.XXXXXX)

test_multi_session
out=$?
if [ $out -ne 0 ]; then
	stop_lttng_sessiond
	exit $out
fi

stop_lttng_sessiond

rm -rf "$TRACE_PATH"
