#!/bin/bash
# run_benchmark.sh — run thread schedulers N times and print mean (ms).
#
# Same argument order as ./shm_benchmark, plus the number of runs at the end:
#   ./run_benchmark.sh F H W K affinity runs [--only NAME]
#
# Examples:
#   ./run_benchmark.sh 1000 640 640 24 1 5                # all thread schedulers
#   ./run_benchmark.sh 1000 640 640 24 1 5 --only aimd    # just aimd
#   ./run_benchmark.sh 1000 640 640 24 1 5 --only guided

if [ $# -lt 6 ] || [ $# -gt 8 ]; then
    echo "Usage: $0 F H W K affinity runs [--only NAME]"
    echo "Example: $0 1000 640 640 24 1 5"
    echo "         $0 1000 640 640 24 1 5 --only aimd"
    exit 1
fi

F=$1
H=$2
W=$3
K=$4
AFFINITY=$5
RUNS=$6
ONLY=""
if [ "$7" = "--only" ] && [ -n "$8" ]; then
    ONLY=$8
fi

if [ ! -x ./shm_benchmark ] || [ ! -x ./shm_generator ]; then
    echo "Error: shm_benchmark or shm_generator not found in current dir."
    echo "Run 'make' first."
    exit 1
fi

# Thread schedulers — filter to one if --only was given.
ALL_SCHEDS=("static" "dynamic" "chunk" "chunk_steal" "guided" "adaptive" "aimd")
THREAD_SCHEDS=()
if [ -n "$ONLY" ]; then
    THREAD_SCHEDS=("$ONLY")
else
    THREAD_SCHEDS=("${ALL_SCHEDS[@]}")
fi

OUTDIR=bench_results
mkdir -p "$OUTDIR"
STAMP=$(date +%Y%m%d_%H%M%S)
LOG="$OUTDIR/threads_${STAMP}_F${F}_H${H}_W${W}_K${K}_aff${AFFINITY}.log"

echo "=========================================="
echo "Thread schedulers benchmark"
echo "F=$F H=$H W=$W K=$K affinity=$AFFINITY runs=$RUNS"
echo "Log: $LOG"
echo "=========================================="

echo ""
echo "Preparing shared memory..."
./shm_generator delete > /dev/null
./shm_generator "$F" "$H" "$W" > /dev/null
echo "SHM ready."
echo ""

> "$LOG"
for ((r=1; r<=RUNS; r++)); do
    echo "----- Run $r/$RUNS -----"
    echo "----- Run $r/$RUNS -----" >> "$LOG"
    for sched in "${THREAD_SCHEDS[@]}"; do
        ./shm_benchmark "$F" "$H" "$W" "$K" "$AFFINITY" --only "$sched" \
            | grep "sorted=" | tee -a "$LOG"
    done
    echo ""
done

echo "=========================================="
echo "Mean execution time (ms) over $RUNS runs"
echo "=========================================="

awk '
    /sorted=(yes|NO)/ {
        name = $1
        ms = $2 + 0
        sum[name] += ms
        count[name]++
    }
    END {
        printf "%-16s  %8s\n", "Scheduler", "mean(ms)"
        printf "%-16s  %8s\n", "----------------", "--------"
        order = "static dynamic chunk chunk_steal guided adaptive aimd"
        n = split(order, names, " ")
        for (i = 1; i <= n; i++) {
            name = names[i]
            if (count[name] > 0) {
                printf "%-16s  %8.1f\n", name, sum[name] / count[name]
            }
        }
    }
' "$LOG"

echo ""
echo "Full log saved to: $LOG"
