#!/bin/bash
#
# Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
#
# SPDX-License-Identifier: LGPL-2.1-only

TEST_DESC="UST - Namespace contexts"

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

TESTAPP_PATH="$TESTDIR/utils/testapp"
TESTAPP_NAME="gen-ust-events"
TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
NUM_EVENT=1000
EVENT_NAME="tp:tptest"

TESTS_PER_NS=13

NUM_TESTS=$((TESTS_PER_NS * 8))

source "$TESTDIR/utils/utils.sh"

# MUST set TESTDIR before calling those functions
function run_app()
{
	$TESTAPP_BIN -i $NUM_EVENT
	ok $? "Application done"
}

function test_ns()
{
	local ns=$1

	local session_name="${ns}_ns"
	local chan_name="${ns}_ns"
	local context_name="${ns}_ns"
	local trace_path
	local ns_inode

	# Check if the kernel has support for this ns type
	if [ ! -f "/proc/$$/ns/$ns" ]; then
		skip 0 "System has no $ns namespace support" $TESTS_PER_NS
		return
	fi

	trace_path=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")

	# Get the current ns inode number
	ns_inode=$(stat -c '%i' -L "/proc/$$/ns/$ns")
	ok $? "Get current $ns namespace inode: $ns_inode"

	start_lttng_sessiond

	create_lttng_session_ok "$session_name" "$trace_path"
	enable_ust_lttng_channel_ok "$session_name" "$chan_name"
	add_context_ust_ok "$session_name" "$chan_name" "$context_name"
	enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$chan_name"
	start_lttng_tracing_ok "$session_name"

	run_app

	# stop and destroy
	stop_lttng_tracing_ok "$session_name"
	destroy_lttng_session_ok "$session_name"
	stop_lttng_sessiond

	# Check that the events contain the right namespace inode number
	validate_trace_count "${ns}_ns = $ns_inode" "$trace_path" $NUM_EVENT

	rm -rf "$trace_path"
}


plan_tests $NUM_TESTS

print_test_banner "$TEST_DESC"

system_has_ns=0
if [ -d "/proc/$$/ns" ]; then
	system_has_ns=1
fi

skip $system_has_ns "System does not support namespaces" $NUM_TESTS && exit 0

test_ns cgroup
test_ns ipc
test_ns mnt
test_ns net
test_ns pid
test_ns time
test_ns user
test_ns uts
