#!/bin/bash
#
# SPDX-FileCopyrightText: 2016 Julien Desfossez <jdesfossez@efficios.com>
# SPDX-FileCopyrightText: 2025 Michael Jeanson <mjeanson@efficios.com>
#
# SPDX-License-Identifier: LGPL-2.1-only

TEST_DESC="Regenerate the statedump - User-space tracing"

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

NR_ITER=10
NR_USEC_WAIT=0

TESTAPP_PATH="$TESTDIR/utils/testapp"
TESTAPP_NAME="gen-ust-events"
TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME"
TESTAPP_TIMEOUT_SEC=10

NUM_TESTS=13

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

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

function test_regenerate_statedump_ust ()
{
	local session_name="regen-statedump-ust"
	local event_name="lttng_ust_statedump:start,lttng_ust_statedump:end"

	local ret
	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")

	diag "Test UST local with statedump regeneration"

	create_lttng_session_ok $session_name "$trace_path"
	enable_ust_lttng_event_ok $session_name $event_name

	"$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"

	start_lttng_tracing_ok $session_name

	# 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"

	regenerate_statedump_ok $session_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

	validate_trace_count $event_name "$trace_path" 4

	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"
bail_out_if_no_babeltrace

start_lttng_sessiond

test_regenerate_statedump_ust

stop_lttng_sessiond
