#!/bin/bash
# parameter 1: table id
# parameter 2: changefeed id
# parameter 3: retry count

set -euo pipefail
set -x

tableID=${1}
changefeedID=${2}
retryCount=${3}
mode=${4:-0}

echo "split table with retry"
count=0

while [[ $count -lt $retryCount ]]; do
	# cdc cli may output logs or other non-JSON content; extract the last JSON object with "success".
	result=$(cdc_cli_changefeed split-table-by-region-count -c "$changefeedID" -t "$tableID" --mode "$mode" 2>&1 || true)
	echo "$result"
	success=$(
		printf '%s' "$result" |
			jq -Rrs '
				# scan returns a *stream* (not an array) in jq, and its regex flags do not support dotall.
				# Use "[\\s\\S]" to match across newlines so pretty-printed JSON objects are detected.
				([scan("\\{[\\s\\S]*?\\}") | try (fromjson | select(type=="object" and has("success"))) catch empty] | last | .success) // false
			'
	)

	if [ "$success" = "true" ]; then
		exit 0
	fi

	count=$((count + 1))
	sleep 1
done

echo "split table $tableID failed after $retryCount retries"
exit 1
