#!/bin/bash
#
# run_bench.sh - Run the complete zero-copy benchmark suite.
#
# Outputs CSV to stdout. Redirect to file for analysis:
#   ./run_bench.sh > results.csv
#
# Part of: https://2b.ai post/linux/zero-copy-dirty-truth

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# Build if needed
if [[ ! -f bench_readwrite ]] || [[ ! -f bench_sendfile ]] || \
   [[ ! -f bench_splice ]] || [[ ! -f bench_iouring_zc ]]; then
    echo "Building benchmarks..." >&2
    make -j"$(nproc)" >&2
fi

# Test parameters
SIZES=(64 512 4096 16384 65536 262144 1048576 10485760)
BASE_PORT=9100
WARMUP=3
RUN=10

# Print environment info to stderr
echo "=== Zero-Copy Benchmark Suite ===" >&2
echo "Kernel: $(uname -r)" >&2
echo "CPU:    $(grep 'model name' /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)" >&2
echo "Date:   $(date -Iseconds)" >&2
echo "Warmup: ${WARMUP}s  Run: ${RUN}s" >&2
echo "Sizes:  ${SIZES[*]}" >&2
echo "=================================" >&2
echo "" >&2

# CSV header
echo "method,data_size,bytes_sent,ops,elapsed_sec,throughput_mbps,ops_per_sec"

PORT=$BASE_PORT

for SIZE in "${SIZES[@]}"; do
    echo "--- Testing size: $SIZE bytes ---" >&2

    for BENCH in bench_readwrite bench_sendfile bench_splice bench_iouring_zc; do
        PORT=$((PORT + 1))
        if [[ $PORT -gt 9200 ]]; then
            PORT=9101
        fi

        echo "  Running: $BENCH (size=$SIZE, port=$PORT)" >&2

        # Run benchmark, capture CSV output
        ./"$BENCH" "$SIZE" "$PORT" "$WARMUP" "$RUN" 2>/dev/null || {
            echo "  WARN: $BENCH failed for size=$SIZE (may need root or newer kernel)" >&2
        }

        # Brief pause between tests to let TCP TIME_WAIT clear
        sleep 1
    done

    echo "" >&2
done

echo "=== Benchmark complete ===" >&2
echo "Results are in CSV format above." >&2
echo "Analyze with: python3 -c 'import pandas as pd; df=pd.read_csv(\"results.csv\"); print(df.pivot_table(values=\"throughput_mbps\", index=\"data_size\", columns=\"method\"))'" >&2
