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

PORT="${PORT:-6379}"

services=$(zcli service list 2>/dev/null \
    | awk -F'│' '{gsub(/ /, "", $3); print $3}' \
    | grep -E '^valkey' || true)

if [[ -z "$services" ]]; then
    echo "no valkey* services found" >&2
    exit 1
fi

fail=0
while IFS= read -r svc; do
    echo "=== testing $svc ==="
    password=$(zcli project env --service "$svc" 2>/dev/null \
        | grep -E '^password=' \
        | head -n1 \
        | sed -E 's/^password="?([^"]*)"?$/\1/')
    if [[ -z "$password" ]]; then
        echo "!!! $svc: could not fetch password" >&2
        fail=1
        continue
    fi
    if ! go run ./... -password "$password" -host "${svc}.zerops" -port "$PORT"; then
        echo "!!! $svc FAILED" >&2
        fail=1
    fi
done <<< "$services"

exit "$fail"
