#!/bin/bash
# parameter 1: ip addr with port
# parameter 2: changefeed id
# parameter 3: target count, if target count is -1, means the target count is not important, just not to be null
# parameter 4: retry count
# parameter 5: comparison mode, support le, eq, ge, default is eq

set -ex

ipAddr=${1}
changefeedID=${2}
target=${3}
retryCount=${4}
comparisonMode=${5}
mode=${6:-0}

echo "query dispatcher count"
count=0

while [[ $count -lt $retryCount ]]; do
	ans=$(curl -X GET http://"${ipAddr}"/api/v2/changefeeds/"${changefeedID}"/get_dispatcher_count?mode=$mode\&keyspace=$KEYSPACE_NAME)
	echo $ans
	value=$(echo $ans | jq -r '.count')

	if [ "$target" == "-1" ]; then
		if [ "$value" != "null" ]; then
			exit 0
		fi
	else
		if [ "$comparisonMode" == "le" ]; then
			if [ "$value" -le "$target" ]; then
				exit 0
			fi
		elif [ "$comparisonMode" == "ge" ]; then
			if [ "$value" -ge "$target" ]; then
				exit 0
			fi
		else
			if [ "$value" == "$target" ]; then
				exit 0
			fi
		fi
	fi

	sleep 2

	count=$((count + 1))
done

echo "query dispatcher count $retryCount retries, final value: $value, target: $target"
exit 1
