#!/usr/bin/env bash
# Valkey snapshot-mode persistence test — runs on the WHP server itself.
set -euo pipefail

CUSTOMER="${CUSTOMER:-valkey-qa-snap}"

mysql whp -e "INSERT IGNORE INTO whp.client_allowances (username) VALUES ('$CUSTOMER')"

echo "[1/5] Enable in snapshot mode, 64 MB"
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);
print_r($vk->enable("'"$CUSTOMER"'", ["memory_mb"=>64,"mode"=>"snapshot","eviction_policy"=>"allkeys-lru"], []));
'

echo "[2/5] SET + BGSAVE + stop"
docker exec "valkey-cust-$CUSTOMER" valkey-cli SET persist_key original_value >/dev/null
docker exec "valkey-cust-$CUSTOMER" valkey-cli BGSAVE >/dev/null
sleep 3
docker stop "valkey-cust-$CUSTOMER" >/dev/null

echo "[3/5] Restart + GET (must match)"
docker start "valkey-cust-$CUSTOMER" >/dev/null
sleep 2
got=$(docker exec "valkey-cust-$CUSTOMER" valkey-cli GET persist_key)
[ "$got" = "original_value" ] || { echo "FAIL: got '$got'"; exit 1; }
echo "   OK"

echo "[4/5] dump.rdb present on host"
[ -f "/home/$CUSTOMER/valkey/data/dump.rdb" ] || { echo "FAIL: dump.rdb missing"; exit 1; }
echo "   OK"

echo "[5/5] Clean up"
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);
print_r($vk->disable("'"$CUSTOMER"'", []));
'

echo "ALL PASS"
