#!/usr/bin/env bash

TRACING_USERS="${TRACING_USERS:-1}"
TRACING_USER_1=root
TRACING_USER_2=kstewart
QDISC_DELAY="${QDISC_DELAY:-300ms}"
GEN_WAIT="${GEN_WAIT:-1000000}"

KILL_TIMEOUT="${KILL_TIMEOUT:-3}"
USE_LIBTOOL="${USE_LIBTOOL:-1}"  # Set to 0 to run via search path instead
BT2_PATH="$(realpath "${BT2_PATH:-../babeltrace2}")"
TOOLS_PATH="$(realpath "${TOOLS_PATH:-../lttng-tools}")"
TRACE_DIR="$(realpath "${TRACE_DIR:-./trace}")"

BABELTRACE_LOG_FILE="$(realpath "${BABELTRACE_LOG_FILE:-babeltrace.log}")"
RELAYD_LOG_FILE="$(realpath "${RELAYD_LOG_FILE:-relayd.log}")"
SESSIOND_LOG_FILE="$(realpath "${SESSIOND_LOG_FILE:-sessiond.log}")"

babeltrace="$(command -v babeltrace2)"
lttng="$(command -v lttng)"
lttng_sessiond="$(command -v lttng-sessiond)"
lttng_relayd="$(command -v lttng-relayd)"
gen_ust="${TOOLS_PATH}/tests/utils/testapp/gen-ust-events/gen-ust-events"

if [[ "${USE_LIBTOOL}" != "0" ]] ; then
    babeltrace="libtool --mode=execute ${BT2_PATH}/src/cli/babeltrace2"
    lttng="libtool --mode=execute ${TOOLS_PATH}/src/bin/lttng/lttng"
    lttng_sessiond="libtool --mode=execute ${TOOLS_PATH}/src/bin/lttng-sessiond/lttng-sessiond"
    lttng_relayd="libtool --mode=execute ${TOOLS_PATH}/src/bin/lttng-relayd/lttng-relayd"
    gen_ust="libtool --mode=execute ${gen_ust}"
fi

function _stop_by_pgrep()
{
    local PROC="${1}"
    local RETRY_INTERVAL="${3:-1}"
    local TIMEOUT="${2:-${KILL_TIMEOUT}}"
    local TRIES=0

    while pgrep "${PROC}" ; do
        if [[ "${TRIES}" -gt "${TIMEOUT}" ]] ; then
            killall -9 "${PROC}"
            sleep "${RETRY_INTERVAL}"
            continue
        fi
        killall "${PROC}"
        sleep "${RETRY_INTERVAL}"
        TRIES=$((TRIES+1))
    done
}

function stop_sessiond()
{
    _stop_by_pgrep lttng-sessiond
}

function stop_relayd()
{
    _stop_by_pgrep lttng-relayd
}

rm "${BABELTRACE_LOG_FILE}"
rm "${RELAYD_LOG_FILE}"
rm "${SESSIOND_LOG_FILE}"
rm -rf "${TRACE_DIR:-}"

$lttng_sessiond -vvv --verbose-consumer &> "${SESSIOND_LOG_FILE}" &
sleep 3

TRACEE_PIDS=()

TRACED_APPS_COUNT=0
for i in $(seq $TRACING_USERS) ; do
    VAR_NAME="TRACING_USER_$i"
    if [[ -n "${!VAR_NAME}" ]] ; then
        su "${!VAR_NAME}" -- $gen_ust -i 10000000 -w $GEN_WAIT &
        TRACEE_PIDS+=($!)
        TRACED_APPS_COUNT=$((TRACED_APPS_COUNT+1))
    fi
done

$lttng create --live
$lttng enable-event -u --all
$lttng start

START="$(date +%s.%N)"
tc qdisc add dev lo root netem delay $QDISC_DELAY
time $lttng destroy
END="$(date +%s.%N)"

echo -e "$TRACED_APPS_COUNT\t$QDISC_DELAY\t$START\t$END\t$(bc <<< "$END - $START")" >> results
# Cleanup
stop_sessiond
_stop_by_pgrep gen-ust-events
tc qdisc del dev lo root
kill "${TRACEE_PIDS[@]}"
