#!/bin/bash
set -e
echo "INFO: Starting Perfetto autopkgtest"

# Start services
echo "INFO: Starting traced and traced_probes services..."
systemctl start traced.service
systemctl start traced-probes.service

# Run perfetto to capture a short trace
TRACE_FILE=$(mktemp --suffix=.pftrace)
echo "INFO: Capturing trace to ${TRACE_FILE}..."
perfetto --txt -c - -o "${TRACE_FILE}" <<EOF
duration_ms: 1000
buffers: {
    size_kb: 896
    fill_policy: DISCARD
}
data_sources: {
    config: {
        name: "linux.ftrace"
        ftrace_config: {
            ftrace_events: "sched/sched_switch"
            atrace_categories: "sched"
        }
    }
}
EOF

# Check if trace file was created and is not empty
if [ ! -s "${TRACE_FILE}" ]; then
    echo "ERROR: Trace file is missing or empty!"
    exit 1
fi
echo "INFO: Trace file created and is not empty."

# Cleanup
echo "INFO: Cleaning up..."
rm -f "${TRACE_FILE}"
systemctl stop traced.service
systemctl stop traced-probes.service

echo "INFO: Perfetto autopkgtest finished successfully"
exit 0
