#!/usr/bin/env bash
# Valkey load probe — runs on the WHP server itself.
# Provisions 5 throwaway customers at 128 MB each, benchmarks one with memtier,
# observes others + a live site URL for cross-tenant impact, tears down.
set -euo pipefail

SITE_URL="${SITE_URL:-https://localhost/ping}"
CUSTS=(vk-probe-1 vk-probe-2 vk-probe-3 vk-probe-4 vk-probe-5)

echo "[1/5] Provision 5 throwaway customers with Valkey @ 128 MB"
for C in "${CUSTS[@]}"; do
    mysql whp -e "INSERT IGNORE INTO whp.client_allowances (username) VALUES ('$C')"
    php -r '
require_once "/docker/whp/web/configs/config.php";
require_once "/docker/whp/web/libs/mysqlmgmt.php";
require_once "/docker/whp/web/libs/valkey-mgmt.php";
$db = (new mysqlmgmt())->getMySQLConnection();
$vk = new ValkeyMgr($db);
$vk->enable("'"$C"'", ["memory_mb"=>128,"mode"=>"cache","eviction_policy"=>"allkeys-lru"], []);
'
done

echo "[2/5] Baseline site response time (3 samples)"
for i in 1 2 3; do curl -sk -o /dev/null -w "baseline: %{time_total}\n" "$SITE_URL"; done

echo "[3/5] Benchmark customer 1 with memtier"
TARGET_C="${CUSTS[0]}"
docker run --rm --network "cust-$TARGET_C-valkey-net" redislabs/memtier_benchmark:latest \
    -s valkey -p 6379 --threads=2 --clients=5 --requests=5000 --data-size=1024 --ratio=1:1 --hide-histogram

echo "[4/5] During load: other Valkey instances + live site"
for C in "${CUSTS[@]:1}"; do
    docker exec "valkey-cust-$C" valkey-cli INFO stats | grep -E 'instantaneous_ops|total_connections' || true
done
for i in 1 2 3; do curl -sk -o /dev/null -w "during-load: %{time_total}\n" "$SITE_URL"; done

echo "[5/5] Teardown"
for C in "${CUSTS[@]}"; do
    php -r '
require_once "/docker/whp/web/configs/config.php";
require_once "/docker/whp/web/libs/mysqlmgmt.php";
require_once "/docker/whp/web/libs/valkey-mgmt.php";
$db = (new mysqlmgmt())->getMySQLConnection();
$vk = new ValkeyMgr($db);
$vk->disable("'"$C"'", []);
'
done

echo "Probe complete. Compare baseline vs during-load times manually."
