#!/bin/bash
#
# Copyright (C) - 2012 Christian Babeux <christian.babeux@efficios.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License, version 2 only, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

TEST_DESC="Health check - Thread exit"

CURDIR=$(dirname $0)/
TESTDIR=$CURDIR/../../..
LTTNG_BIN="lttng"
SESSION_NAME="health_thread_exit"
EVENT_NAME="bogus"
HEALTH_CHECK_BIN="health_check"
SESSIOND_PRELOAD=".libs/libhealthexit.so"
NUM_TESTS=12

source $TESTDIR/utils/utils.sh

if [ ! -f "$CURDIR/$SESSIOND_PRELOAD" ]; then
	BAIL_OUT "libhealthexit.so not available for this test."
fi

function test_thread_exit
{
	test_thread_exit_name="$1"
	test_thread_exit_code="$2"

	diag "Test health failure with ${test_thread_exit_name}"

	# Activate testpoints
	export LTTNG_TESTPOINT_ENABLE=1

	# Activate specific thread exit
	export ${test_thread_exit_name}_EXIT=1

	# Spawn sessiond with preload healthexit lib
	export LD_PRELOAD="$CURDIR/$SESSIOND_PRELOAD"
	# Set the socket timeout to 5 so the health check delta is set to 25.
	export LTTNG_NETWORK_SOCKET_TIMEOUT=5
	start_lttng_sessiond

	# Cleanup some env. var.
	unset LD_PRELOAD
	unset ${test_thread_exit_name}_EXIT

	# Check initial health status
	$CURDIR/$HEALTH_CHECK_BIN &> /dev/null

	# Wait
	sleep 30

	# Check health status, exit code should indicate failure
	$CURDIR/$HEALTH_CHECK_BIN &> /dev/null

	health_check_exit_code=$?

	if [ $health_check_exit_code -eq $test_thread_exit_code ]; then
		pass "Validate thread ${test_thread_exit_name} failure"
		stop_lttng_sessiond
	else
		fail "Validate thread ${test_thread_exit_name} failure"

		diag "Health returned: $health_check_exit_code\n"

		stop_lttng_sessiond
		return 1
	fi
}

plan_tests $NUM_TESTS

print_test_banner "$TEST_DESC"

THREAD=("LTTNG_THREAD_MANAGE_CLIENTS"
	"LTTNG_THREAD_MANAGE_APPS"
	"LTTNG_THREAD_REG_APPS")

# Exit code value to indicate specific thread failure
EXIT_CODE=(1 2 4)

THREAD_COUNT=${#THREAD[@]}
i=0
while [ "$i" -lt "$THREAD_COUNT" ]; do
	test_thread_exit "${THREAD[$i]}" "${EXIT_CODE[$i]}"

	if [ $? -eq 1 ]; then
		exit 1
	fi

	let "i++"
done

# The manage kernel thread is only spawned if we are root
if [ "$(id -u)" == "0" ]; then
	isroot=1
else
	isroot=0
fi

skip $isroot "Root access is needed. Skipping LTTNG_THREAD_MANAGE_KERNEL tests." "3" ||
{
	test_thread_exit "LTTNG_THREAD_MANAGE_KERNEL" "8"
}


# TODO: Special case manage consumer, need to spawn consumer via commands.
#"LTTNG_THREAD_MANAGE_CONSUMER"
