#!/bin/bash
# The script generated by PIPA-TREE is used to collect performance data.
# Please check whether it meets expectations before running.
# ZJU SPAIL(https://github.com/ZJU-SPAIL) reserves all rights.
# Generated at 2025-09-08T20:57:59.810537

# Check if sar and perf are available
if ! command -v sar &> /dev/null; then
echo "sar command not found. Please install sar."
exit 1
fi

if ! command -v perf &> /dev/null; then
echo "perf command not found. Please install perf."
exit 1
fi

WORKSPACE=./pipa-data/
# Check if $workspace exists
if [ -d "$workspace" ]; then
  # Check if perf-stat.csv or sar.dat exists in $workspace
  if [ -f "$workspace/perf-stat.csv" ] || [ -f "$workspace/sar.dat" ]; then
    # Move $workspace to $workspace_old
    mv "$workspace" "${workspace}_old"
  fi
fi
mkdir -p $WORKSPACE

ps -aux -ef --forest > $WORKSPACE/ps.txt

MODE=${1:-counting}

if [ "$MODE" = "counting" ] || [ "$MODE" = "" ]; then
  # Execute counting mode commands
  sar -A -o $WORKSPACE/sar.dat 1 >/dev/null 2>&1 &
  sar_pid=$!
  perf stat -e cycles:D,instructions:D,ref-cycles:D -A -x , -I 1000 -o $WORKSPACE/perf-stat.csv
  kill -9 $sar_pid
elif [ "$MODE" = "profiling" ]; then
  # Execute profiling mode commands
  perf record -e '{cycles,instructions}:S' -g -a --call-graph dwarf -N -F 997 -o $WORKSPACE/perf.data
else
  # Invalid parameter
  echo "Invalid parameter. Usage: $0 [counting|profiling]"
exit 1
fi

echo 'Performance data collected successfully.'