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

# 简化版 pgbench 测试脚本：
# 1) 参数都在本文件顶部配置；
# 2) 直接连接 benchdb；
# 3) 执行 pgbench 初始化和压测。

# ---------------------------
# 固定配置（按需改这里）
# ---------------------------
PG_HOST="127.0.0.1"
PG_PORT="5432"
PG_DB="benchdb"
PG_SCALE="10"
PG_TIME="20"
PG_CLIENTS="2"
PG_SUPERUSER="postgres"
USE_LD_PRELOAD="1"
LD_PRELOAD_PATH="/home/lian/try/zvfs/src/libzvfs.so"

# 可选：优先使用这个目录；为空时自动从 PATH 里找
PG_BIN_DIR="/usr/lib/postgresql/12/bin"

if [[ ! -x "${PG_BIN_DIR}/pgbench" ]]; then
  PG_BIN_DIR="$(dirname "$(command -v pgbench 2>/dev/null || true)")"
fi

if [[ -z "${PG_BIN_DIR}" || ! -x "${PG_BIN_DIR}/pgbench" ]]; then
  echo "未找到 pgbench，请先安装 PostgreSQL 客户端或修正 PG_BIN_DIR。" >&2
  exit 1
fi

run_pg_cmd() {
  if [[ "${USE_LD_PRELOAD}" == "1" ]]; then
    sudo -u "${PG_SUPERUSER}" env LD_PRELOAD="${LD_PRELOAD_PATH}" "$@"
  else
    sudo -u "${PG_SUPERUSER}" "$@"
  fi
}

echo "当前配置："
echo "  host=${PG_HOST} port=${PG_PORT} db=${PG_DB}"
echo "  scale=${PG_SCALE} clients=${PG_CLIENTS} time=${PG_TIME}s preload=${USE_LD_PRELOAD}"
echo

echo "[1/2] pgbench 初始化（-i）"
run_pg_cmd "${PG_BIN_DIR}/pgbench" \
  -h "${PG_HOST}" -p "${PG_PORT}" -i -s "${PG_SCALE}" "${PG_DB}"

echo "[2/2] pgbench 压测（-T）"
run_pg_cmd "${PG_BIN_DIR}/pgbench" \
  -h "${PG_HOST}" -p "${PG_PORT}" -c "${PG_CLIENTS}" -T "${PG_TIME}" "${PG_DB}"
