set -e
# Example script allowing local verifiaction of the system_monitor node vs ftrace.
# Useful for quickly iterating on event types, and validating their correctness vs
# existing tracepoints included in linux.
# Will likely require local modifications for your own dev testing.

# To use:
#
# run ./test_bpf.sh
# examine log files generated in ~/.log/ftrace/{ftrace,bpf.sort.log} in Chrome Traceview or
# your favorite text editor and confirm if the generated events match

# bazel build //vehicle:l3_deploy_package //bin/...
# ./scripts/vehicle/ftrace_enable.sh

rm /tmp/chum/ -r || true
rm $HOME/.cache/chum/ -r || true
mkdir -p /tmp/chum

bazel build //vehicle:l3_deploy_package //bin/...
bazel build //vehicle:l3_deploy_package //logger:record_chum

roscore &
sleep 1;

# enable the events you want to validate against here
echo 0      | sudo tee /sys/kernel/debug/tracing/events/sched/sched_wakeup/enable
echo 0      | sudo tee /sys/kernel/debug/tracing/events/sched/sched_switch/enable

echo 1      | sudo tee /sys/kernel/debug/tracing/free_buffer
echo 2048   | sudo tee /sys/kernel/debug/tracing/buffer_size_kb

sudo -E -b bazel-bin/vehicle/bpf_system_monitor/system_monitor_node --deescalate_username=`whoami`
record_chum --variant "" &

# wait until node and logger are stable..
sleep 10
rostopic list
echo "Start"
start=`date +%s.%N`

sleep 1

pkill -SIGINT --full system_monitor_node || true
pkill -SIGINT --full record_chum || true
pkill -SIGINT --full roscore.py || true

# wait for shutdown
sleep 5

end=`date +%s.%N`

bazel run //scripts/tools/trace/bpf_to_ftrace -- chum://hero@$start-$end?i=/tmp/chum > $HOME/.log/ftrace/bpf_only.log --noinclude_ftrace
bazel run //scripts/tools/trace/bpf_to_ftrace -- chum://hero@$start-$end?i=/tmp/chum > $HOME/.log/ftrace/ftrace_only.log --noinclude_bpf
bazel run //scripts/tools/trace/bpf_to_ftrace -- chum://hero@$start-$end?i=/tmp/chum > $HOME/.log/ftrace/bpf.log

echo Done
