#!/bin/bash

avg_bw() {
    # Pass the type of operation (read/write) as an argument
    op_type=$1

    # Depending on the operation type (read/write), extract the correct bandwidth data
    avg_bw=$(jq -s "map(.jobs[0].$op_type.bw) | add / length / 1024 * 100 | round / 100" output_dir/run*.json)
    echo "Average: $avg_bw MB/s"
}

# Define all test configurations in an array
tests=(
    "--rw=read --bs=1M --iodepth=8"
    "--rw=write --bs=1M --iodepth=8"
    "--rw=read --bs=1M --iodepth=1"
    "--rw=write --bs=1M --iodepth=1"
    "--rw=randread --bs=4K --iodepth=32"
    "--rw=randwrite --bs=4K --iodepth=32"
    "--rw=randread --bs=4K --iodepth=1"
    "--rw=randwrite --bs=4K --iodepth=1"
)

# Create a new directory for this test run to store the output
test_dir="output_dir"
mkdir -p "$test_dir"  # Create the test directory

# Outer loop to iterate through the 8 test configurations
for j in "${!tests[@]}"; do
    echo "Running test $((j+1)) with configuration: ${tests[$j]}"
    
    # Determine if it's a read or write test
    if [[ "${tests[$j]}" == *"read"* ]]; then
        op_type="read"
    elif [[ "${tests[$j]}" == *"write"* ]]; then
        op_type="write"
    fi

    # Inner loop to run fio 5 times per test
    for i in {1..5}; do
        echo "  Running iteration $i"
        fio --name=testfile --ioengine=libaio --numjobs=1 --size=256M --runtime=10 --time_based=1 --filename=output_dir/testfile ${tests[$j]} --output="$test_dir/run$i.json" --output-format=json --direct=1 > /dev/null 2>&1
        spd=$(jq -s "map(.jobs[0].$op_type.bw) | add / 1024 * 100 | round / 100" "$test_dir/run$i.json")
	echo "  Iteration $i: $spd MB/s"
    done

    # Calculate and display the average bandwidth for the current test
    avg_bw "$op_type"

done
# Clean up: remove the directory after the test
rm -rf "$test_dir"
