#!/bin/bash
#
# SPDX-FileCopyrightText: 2023 Kienan Stewart <kstewart@efficios.com>
#
# SPDX-License-Identifier: LGPL-2.1-only
#

TEST_DESC="lttng-sessiond should not crash when activating rules that different by loglevel only"

CURDIR=$(dirname "$0")
TESTDIR=${CURDIR}/../../..

# Test app for ust event
TESTAPP_PATH="${TESTDIR}/utils/testapp"
TESTAPP_NAME="gen-ust-events"
TESTAPP_BIN="${TESTAPP_PATH}/${TESTAPP_NAME}"
TESTAPP_TIMEOUT_SEC=10

NR_USEC_WAIT=1
NR_ITER=100

EVENT_NAME="'l*'"

NUM_TESTS=11

# shellcheck source-path=SCRIPTDIR/../../../
source "${TESTDIR}/utils/utils.sh"

function test_events_differ_only_by_loglevels ()
{
	local session_name="test_session"
	local channel_name="test_channel"
	local testapp_pid
	local trace_path
	local file_testapp_output
	local file_sync_after_first
	local file_sync_before_last
	local file_sync_before_exit_touch

	trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
	file_testapp_output=$(mktemp -u -t "tmp.${FUNCNAME[0]}_testapp_output.XXXXXX")
	file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
	file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
	file_sync_before_exit_touch=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_exit_touch.XXXXXX")

	start_lttng_sessiond

	"$TESTAPP_BIN" -i $NR_ITER -w $NR_USEC_WAIT \
		--sync-after-first-event "${file_sync_after_first}" \
		--sync-before-last-event "${file_sync_before_last}" \
		--sync-before-exit-touch "${file_sync_before_exit_touch}" >"${file_testapp_output}" 2>&1 &
	testapp_pid=$!
	diag "Launched testapp '$TESTAPP_NAME' (pid: $testapp_pid) to generate $NR_ITER events"

	# Wait for the testapp first event
	app_alive_wait_for_sync "$TESTAPP_NAME" "$testapp_pid" "$TESTAPP_TIMEOUT_SEC" "$file_testapp_output" "$file_sync_after_first"

	create_lttng_session_ok "${session_name}" "${trace_path}"
	enable_ust_lttng_channel_ok "${session_name}" "${channel_name}"
	start_lttng_tracing_ok "${session_name}"

	enable_ust_lttng_event_loglevel "${session_name}" "${EVENT_NAME}" TRACE_DEBUG_LINE "${channel_name}"
	enable_ust_lttng_event_loglevel_only "${session_name}" "${EVENT_NAME}" TRACE_DEBUG_LINE "${channel_name}"

	# Tell the testapp to continue
	touch "${file_sync_before_last}"

	app_exit_wait_for_sync "$TESTAPP_NAME" "$testapp_pid" "$TESTAPP_TIMEOUT_SEC" "$file_testapp_output" "$file_sync_before_exit_touch"

	stop_lttng_tracing_ok "${session_name}"
	destroy_lttng_session_ok "${session_name}"

	stop_lttng_sessiond

	rm -rf "${trace_path}"
	rm -f "$file_testapp_output"
	rm -f "$file_sync_after_first"
	rm -f "$file_sync_before_last"
	rm -f "$file_sync_before_exit_touch"
}


plan_tests "${NUM_TESTS}"
print_test_banner "${TEST_DESC}"

if [ ! -x "${TESTAPP_BIN}" ] ; then
    BAIL_OUT "No UST events binary detected"
fi

test_events_differ_only_by_loglevels
