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

: "${HOST:?HOST must be set in the environment (example: HOST=<db-host>)}"
PORT="${PORT:-4000}"
: "${DB_USER:?DB_USER must be set in the environment (example: DB_USER=<db-user>)}"
: "${DB_PASSWORD:?DB_PASSWORD must be set in the environment (example: DB_PASSWORD=<db-password>)}"
DURATION_SEC="${DURATION_SEC:-120}"
CONCURRENCY="${CONCURRENCY:-6}"

MYSQL_BASE=(mysql --connect-timeout=5 --ssl-mode=REQUIRED -h "${HOST}" -P "${PORT}" -u "${DB_USER}" -p"${DB_PASSWORD}")

echo "[load-test] target=${HOST}:${PORT} user=${DB_USER} duration=${DURATION_SEC}s concurrency=${CONCURRENCY}"

echo "[load-test] init schema/table..."
"${MYSQL_BASE[@]}" -e "CREATE DATABASE IF NOT EXISTS hermes_loadtest;"
"${MYSQL_BASE[@]}" -e "CREATE TABLE IF NOT EXISTS hermes_loadtest.t_hot (id BIGINT PRIMARY KEY AUTO_RANDOM, k BIGINT, v VARCHAR(128), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, KEY idx_k(k));"

END_TS=$(( $(date +%s) + DURATION_SEC ))
PIDS=()

worker() {
  local wid="$1"
  local i=0
  while [[ $(date +%s) -lt ${END_TS} ]]; do
    i=$((i+1))
    "${MYSQL_BASE[@]}" -e "
      INSERT INTO hermes_loadtest.t_hot(k,v) VALUES (FLOOR(RAND()*100000), CONCAT('w${wid}-',UUID()));
      SELECT COUNT(*) FROM hermes_loadtest.t_hot WHERE k BETWEEN FLOOR(RAND()*90000) AND FLOOR(RAND()*100000);
      UPDATE hermes_loadtest.t_hot SET v=CONCAT(v,'-u') WHERE k=FLOOR(RAND()*100000) LIMIT 5;
    " >/dev/null 2>&1 || true

    if (( i % 10 == 0 )); then
      "${MYSQL_BASE[@]}" -e "SELECT SLEEP(0.2);" >/dev/null 2>&1 || true
    fi
  done
}

echo "[load-test] starting workers..."
for w in $(seq 1 "${CONCURRENCY}"); do
  worker "${w}" &
  PIDS+=("$!")
done

for pid in "${PIDS[@]}"; do
  wait "${pid}" || true
done

echo "[load-test] finished. quick check:"
"${MYSQL_BASE[@]}" -e "SELECT COUNT(*) AS total_rows, MIN(ts) AS min_ts, MAX(ts) AS max_ts FROM hermes_loadtest.t_hot;"
