#!/usr/bin/env bash
set -euxo pipefail

# reset & configure buffer
echo "0"        | sudo tee /sys/kernel/debug/tracing/tracing_on
echo ""         | sudo tee /sys/kernel/debug/tracing/set_event
echo "nop"      | sudo tee /sys/kernel/debug/tracing/current_tracer
echo ""         | sudo tee /sys/kernel/debug/tracing/trace
echo "1"        | sudo tee /sys/kernel/debug/tracing/options/overwrite
echo "10240"    | sudo tee /sys/kernel/debug/tracing/buffer_size_kb
echo "mono"     | sudo tee /sys/kernel/debug/tracing/trace_clock


# verify settings
sudo cat /sys/kernel/debug/tracing/current_tracer
sudo cat /sys/kernel/debug/tracing/trace_options


# do the thing
(
    echo "nofunction-fork"      | sudo tee /sys/kernel/debug/tracing/trace_options
    echo "latency-format"       | sudo tee /sys/kernel/debug/tracing/trace_options
    echo "1"                    | sudo tee /sys/kernel/debug/tracing/options/funcgraph-proc
    bpid=$BASHPID
    echo $bpid                  | sudo tee /sys/kernel/debug/tracing/set_ftrace_pid
    echo "function_graph"       | sudo tee /sys/kernel/debug/tracing/current_tracer
    echo ""                     | sudo tee /sys/kernel/debug/tracing/set_graph_function
    echo ""                     | sudo tee /sys/kernel/debug/tracing/set_ftrace_filter
    # echo "1" | sudo tee /sys/kernel/debug/tracing/options/max_graph_depth

    # do nothing with function_graph:
    # echo "1" | sudo tee /sys/kernel/debug/tracing/options/func_stack_trace
    # echo "stacktrace"       | sudo tee /sys/kernel/debug/tracing/trace_options
    # echo "userstacktrace"   | sudo tee /sys/kernel/debug/tracing/trace_options

    echo "1" | sudo tee /sys/kernel/debug/tracing/tracing_on
    set +e
    exec "$@"
)

set -e
echo "0" | sudo tee /sys/kernel/debug/tracing/tracing_on

sudo rm /tmp/trace.log || true
sudo cat /sys/kernel/debug/tracing/trace > /tmp/trace.log
echo "Done. Trace in /tmp/trace.log"

echo "nop"      | sudo tee /sys/kernel/debug/tracing/current_tracer
echo ""         | sudo tee /sys/kernel/debug/tracing/set_ftrace_pid
echo ""         | sudo tee /sys/kernel/debug/tracing/trace
