#!/bin/bash
#
# Copyright (C) 2017 Jonathan Rajotte <jonathan.rajotte-julien@efficios.com>
#
# SPDX-License-Identifier: LGPL-2.1-only

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

TEST_TMPDIR=$(mktemp --tmpdir -d tmp.test_notif_kernel_buffer_usage_dir.XXXXXX)

#This is needed since the testpoint create a pipe with the consumerd type suffixed
TESTPOINT_BASE_PATH=$(readlink -f "$TEST_TMPDIR/lttng.t_p_n")
TESTPOINT_PIPE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "lttng.t_p_n.XXXXXX")
TESTPOINT=$(readlink -f "${CURDIR}/.libs/libpause_consumer.so")
TESTAPP_STATE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "application_state.XXXXXXXXXX")


SESSION_NAME="my_session"
CHANNEL_NAME="my_channel"

NUM_TESTS=99

# shellcheck source=../../../utils/utils.sh
source "$TESTDIR/utils/utils.sh"
# shellcheck source=./util_event_generator.sh
source "$CURDIR/util_event_generator.sh"

function test_buffer_usage_notification
{
	local event_name="lttng_test_filter_event"
	local trace_path
	local page_size
	local consumerd_pipe=()

	trace_path=$(mktemp -d --tmpdir="$TEST_TMPDIR" "tmp.${FUNCNAME[0]}_trace_path.XXXXXXX")
	page_size=$(getconf PAGE_SIZE)

	create_lttng_session_notap $SESSION_NAME "$trace_path"

	lttng_enable_kernel_channel_notap $SESSION_NAME $CHANNEL_NAME \
		--subbuf-size="$page_size"
	enable_kernel_lttng_event_notap $SESSION_NAME $event_name $CHANNEL_NAME

	kernel_event_generator generate_filter_events "$TESTAPP_STATE_PATH" &
	APP_PID=$!

	# This is needed since the testpoint create a pipe with the consumer
	# type suffixed.
	for f in "$TESTPOINT_BASE_PATH"*; do
		consumerd_pipe+=("$f")
	done

	"$CURDIR/notification" 2 LTTNG_DOMAIN_KERNEL $APP_PID "$TESTAPP_STATE_PATH" \
		$SESSION_NAME $CHANNEL_NAME "${consumerd_pipe[@]}"

	destroy_lttng_session_notap $SESSION_NAME

	kill -SIGUSR2 $APP_PID
	wait $APP_PID 2> /dev/null
}

check_skip_kernel_test &&
{
	plan_skip_all "Skipping all tests."
	rm -rf "$TEST_TMPDIR"
	exit 0
}

validate_lttng_modules_present

modprobe lttng-test

# Used on sessiond launch.
LTTNG_SESSIOND_ENV_VARS="LTTNG_TESTPOINT_ENABLE=1 \
	CONSUMER_PAUSE_PIPE_PATH=${TESTPOINT_PIPE_PATH} \
	LD_PRELOAD=${TESTPOINT}"
start_lttng_sessiond_notap

test_buffer_usage_notification

stop_lttng_sessiond_notap
rmmod lttng-test

rm -rf "${consumerd_pipe[@]}" 2> /dev/null
rm -rf "$TEST_TMPDIR"
