#!/usr/bin/env bash
# Valkey cross-customer isolation test — runs on the WHP server itself.
# Provisions two customers with their own Valkey, proves A cannot reach B.
set -euo pipefail

CUSTOMERS=(valkey-qa-a valkey-qa-b)

echo "[1/5] Provision customers A and B with Valkey"
for C in "${CUSTOMERS[@]}"; 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"=>64,"mode"=>"cache","eviction_policy"=>"allkeys-lru"], []);
'
done

echo "[2/5] Write secret to B"
docker exec "valkey-cust-valkey-qa-b" valkey-cli SET secret_of_b hidden >/dev/null

echo "[3/5] A's world can reach its own valkey alias"
docker run --rm --network "cust-valkey-qa-a-valkey-net" alpine sh -c "apk add --quiet redis 2>/dev/null; redis-cli -h valkey PING" | grep -q PONG
echo "   OK"

echo "[4/5] A's world cannot reach B's Valkey"
set +e
docker run --rm --network "cust-valkey-qa-a-valkey-net" alpine sh -c "apk add --quiet redis 2>/dev/null; timeout 3 redis-cli -h valkey-cust-valkey-qa-b GET secret_of_b"
rc=$?
set -e
[ $rc -ne 0 ] || { echo "FAIL: customer A reached customer B's Valkey"; exit 1; }
echo "   OK"

echo "[5/5] Teardown"
for C in "${CUSTOMERS[@]}"; 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 "ALL PASS"
