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

# Usage:
#   ./run_5_reps_k.sh K [affinity]
#
# Example:
#   ./run_5_reps_k.sh 10
#   ./run_5_reps_k.sh 10 0

if [[ $# -lt 1 || $# -gt 2 ]]; then
    echo "Usage: $0 K [affinity: 0|1]"
    exit 1
fi

K="$1"
AFFINITY="${2:-1}"

F=1000
H=640
W=640
REPS=5

if ! [[ "$K" =~ ^[0-9]+$ ]] || [[ "$K" -le 0 ]]; then
    echo "K must be a positive integer."
    exit 1
fi

if ! [[ "$AFFINITY" =~ ^[01]$ ]]; then
    echo "affinity must be 0 or 1."
    exit 1
fi

make

echo "Generating shared memory: F=$F H=$H W=$W"
./shm_generator "$F" "$H" "$W"
echo

for rep in $(seq 1 "$REPS"); do
    echo "=============================="
    echo "Rep $rep/$REPS  |  K=$K  |  F=$F H=$H W=$W  |  affinity=$AFFINITY"
    echo "=============================="

    ./shm_benchmark "$F" "$H" "$W" "$K" "$AFFINITY" \
        | awk '
            /One-to-One Pipe sorting time:/   { print; fflush(); }
            /One-to-Many Pipe sorting time:/  { print; fflush(); }
            /Many-to-Many Pipe sorting time:/ { print; fflush(); }
        '

    echo
done