#!/usr/bin/env bash

set -euo pipefail

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
    printf "Usage: %s <db_root_under_/nvme> [result_csv]\n" "$0"
    exit 1
fi

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
root_dir="$(cd -- "${script_dir}/.." && pwd)"
rocksdb_dir="${root_dir}/rocksdb"

db_root="$1"
result_file="${2:-${script_dir}/benchmark_results.csv}"

warmup_secs="${WARMUP_SECS:-10}"
measure_secs="${MEASURE_SECS:-20}"
prefill_keys="${PREFILL_KEYS:-200000}"
read_path="${READ_PATH:-snapshot}"

if [[ "${db_root}" != /nvme* ]]; then
    printf "db_root must be under /nvme, got: %s\n" "${db_root}" >&2
    exit 1
fi

mkdir -p "${db_root}"
mkdir -p "$(dirname -- "${result_file}")"

(cd "${rocksdb_dir}" && cmake --preset release)
(cd "${rocksdb_dir}" && cmake --build --preset release)

workloads=(W1 W2 W3 W4 W5 W6)
threads=(1 6 12)
profiles=(
  "32 1024"
  "32 16384"
)

for workload in "${workloads[@]}"; do
    for t in "${threads[@]}"; do
        for kv in "${profiles[@]}"; do
            read -r key_size value_size <<< "${kv}"
            run_path="$(mktemp -u -p "${db_root}" "rocksdb_${workload}_${t}_${key_size}_${value_size}_XXXXXX")"
            printf "[rocksdb] workload=%s threads=%s key=%s value=%s path=%s\n" \
              "${workload}" "${t}" "${key_size}" "${value_size}" "${run_path}"
            "${rocksdb_dir}/build/release/rocksdb_bench" \
              --path "${run_path}" \
              --workload "${workload}" \
              --threads "${t}" \
              --key-size "${key_size}" \
              --value-size "${value_size}" \
              --prefill-keys "${prefill_keys}" \
              --warmup-secs "${warmup_secs}" \
              --measure-secs "${measure_secs}" \
              --read-path "${read_path}" \
              --result-file "${result_file}"
        done
    done
done

printf "RocksDB runs finished. Results appended to: %s\n" "${result_file}"
