#!/usr/bin/bash
#
# SPDX-FileCopyrightText: 2024 Kienan Stewart <kstewart@efficios.com>
# SPDX-License-Identifier: GPL-2.0-only
#
# Usage:
#   TEST=systemd ./repro.sh
# 
# Or
#    for i in systemd sessiond all-sessiond tree ; do
#       TEST=$i ./repro.sh
#    done
#

TEST="${TEST:-none}"

function pre_app()
{
	systemctl stop lttng-sessiond
	killall lttng-sessiond gen-ust-events
	sleep 2
}

function run_app()
{
	sleep 2
	lttng create >&2
	lttng enable-event -u --all >&2
	lttng start >&2
	/root/master/src/lttng-tools/tests/utils/testapp/gen-ust-events/gen-ust-events -i 2000000 >&2 &
	echo "${!}"
}

function post_app()
{
	local pid="${1}"
	if [[ -n "${pid}" ]] ; then
		kill "${pid}"
	fi
	pre_app
}

ret=250
APP_PID=''

echo "Starting test ${TEST}" >&2
if [[ "${TEST}" == "systemd" ]] ; then
	pre_app
	MODE="$(systemctl cat lttng-sessiond | grep KillMode | cut -d '=' -f 2-)"
	MODE="${MODE:-cgroup}"
	systemctl start lttng-sessiond
	DATE="$(date "+%Y-%m-%d %H:%M:%S")"
	APP_PID=$(run_app)
	systemctl stop lttng-sessiond
	journalctl -u lttng-sessiond.service -S "${DATE}" -g "leaked" --no-pager
	ret="${?}"
	#Failure to find it is success
	if [[ "${ret}" != "0" ]] ; then
		ret=0
	else
		ret=1
	fi
	echo "Systemd (KillMode: '${MODE}'): ret '${ret}'"
elif [[ "${TEST}" == "sessiond" ]] ; then
	pre_app
	TMPFILE=$(mktemp)
	lttng-sessiond -vvv --verbose-consumer > "${TMPFILE}" 2>&1 &
	pid="${!}"
	sleep 2
	pgrep -f lttng-sessiond
	APP_PID=$(run_app)
	sleep 0.1
	kill ${pid}
	grep "leaked" "${TMPFILE}"
	ret="${?}"
	#Failure to find it is success
	if [[ "${ret}" != "0" ]] ; then
		ret=0
	else
		ret=1
	fi
	echo "Killing single sessiond pid '${pid}' (log: '${TMPFILE}'): ret '${ret}'"
elif [[ "${TEST}" == "all-sessiond" ]] ; then
	pre_app
	TMPFILE=$(mktemp)
	lttng-sessiond -vvv --verbose-consumer > "${TMPFILE}" 2>&1 &
	sleep 2
	PIDS=()
	pgrep -f lttng-sessiond
	while read -r line ; do
		PIDS+=("$line")
	done < <(pgrep -f lttng-sessiond)
	APP_PID=$(run_app)
	sleep 0.1
	kill ${PIDS[@]}
	grep "leaked" "${TMPFILE}"
	#Failure to find it is success
	if [[ "${ret}" != "0" ]] ; then
		ret=0
	else
		ret=1
	fi
	ret="${?}"
	echo "Killing all sessiond pids '${PIDS[@]}' (log: '${TMPFILE}'): ret  '${ret}'"
elif [[ "${TEST}" == "tree" ]] ; then
	pre_app
	TMPFILE=$(mktemp)
	lttng-sessiond -vvv --verbose-consumer > "${TMPFILE}" 2>&1 &
	pid="${!}"
	sleep 2
	pgrep -P $(pgrep lttng-sessiond)
	PIDS=("${pid}")
	APP_PID=$(run_app)
	while read -r line ; do
		PIDS+=("$line")
	done < <(pgrep -P "${pid}")
	kill ${PIDS[@]}
	grep "leaked" "${TMPFILE}"
	ret="${?}"
	#Failure to find it is success
	if [[ "${ret}" != "0" ]] ; then
		ret=0
	else
		ret=1
	fi
	echo "Killing all pids under '${pid}': '${PIDS[@]}' (log: '${TMPFILE}') ret  '${ret}'"
else
	echo "Unknown test '${TEST}'" >&2
	exit $ret
fi
post_app "${APP_PID}"
exit "${ret}"
