#!/usr/bin/env bash

set -eu
set -o pipefail


source "${BASH_SOURCE[0]%/*}"/lib/testing.sh


cid_es="$(container_id elasticsearch)"
cid_hb="$(container_id heartbeat)"

ip_es="$(service_ip elasticsearch)"
ip_hb="$(service_ip heartbeat)"

grouplog 'Wait for readiness of Elasticsearch'
poll_ready "$cid_es" 'http://elasticsearch:9200/' --resolve "elasticsearch:9200:${ip_es}" -u 'elastic:testpasswd'
endgroup

grouplog 'Wait for readiness of Heartbeat'
poll_ready "$cid_hb" 'http://heartbeat:5066/?pretty'  --resolve "heartbeat:5066:${ip_hb}"
endgroup

log 'Searching a document generated by Heartbeat'

query=$( (IFS= read -r -d '' data || echo "$data" | jq -c) <<EOD
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "agent.type": "heartbeat"
          }
        },
        {
          "term": {
            "monitor.type": "http"
          }
        },
        {
          "term": {
            "url.domain": "elasticsearch"
          }
        }
      ]
    }
  }
}
EOD
)

declare -a search_args=( '-s' '-u' 'elastic:testpasswd'
	'http://elasticsearch:9200/heartbeat-*/_search?size=1&pretty'
	'--resolve' "elasticsearch:9200:${ip_es}"
	'-H' 'Content-Type: application/json'
	'-d' "${query}"
)
declare response
declare -i count

echo "curl arguments: ${search_args[*]}"

declare -i was_retried=0

# retry for max 60s (30*2s)
for _ in $(seq 1 30); do
	response="$(curl "${search_args[@]}")"

	set +u  # prevent "unbound variable" if assigned value is not an integer
	count="$(jq -rn --argjson data "${response}" '$data.hits.total.value')"
	set -u

	if (( count > 0 )); then
		break
	fi

	was_retried=1
	echo -n 'x' >&2
	sleep 2
done
if ((was_retried)); then
	# flush stderr, important in non-interactive environments (CI)
	echo >&2
fi

echo "$response"
if (( count == 0 )); then
	echo 'Expected at least 1 document'
	exit 1
fi
