#!/bin/bash

function cmd_ti_wait_available()
{
	local ti_file="${1}"
	local ti_args="${2}"
	local cmd_mod_names="${3}"
	local cmd_hosts="${4}"
	local cmd_indexes="${5}"
	local mods="${6}"
	shift 6

	if [ -z "${2+x}" ]; then
		echo "[cmd wait/available] usage: <cmd> database table [timeout=1200]" >&2
		return 1
	fi

	local db="${1}"
	local table="${2}"

	local timeout='600'
	if [ ! -z "${3+x}" ]; then
		local timeout="${3}"
	fi

	local ti="${integrated}/ops/ti.sh"

	echo "=> wait for ${db}.${table} available in tiflash"

	local tidb_index=`from_mods_random_mod "${mods}" 'tidb'`
	if [ -z "${tidb_index}" ]; then
		echo "[cmd wait/available] no selected tidb" >&2
		return 1
	fi

	local failed='true'
	local query="select available from information_schema.tiflash_replica where table_schema='${db}' and table_name='${table}'"
	for (( i = 0; i < "${timeout}"; i++ )); do
		local available_status=`"${ti}" -h "${cmd_hosts}" -m "tidb" -i "${tidb_index}" -k "${ti_args}" \
			"${ti_file}" 'mysql' "${query}" "${db}" false | trim_host | { grep "1" || test $? = 1; } | wc -l`
		if [ ${?} == 0 ] && [ "${available_status}" -eq 1 ]; then
			local failed='false'
			break
		fi
		if [ $((${i} % 10)) = 0 ] && [ ${i} -ge 10 ]; then
			echo "   #${i} waiting for ${db}.${table} learner storage available"
			local current_progress=`"${ti}" -h "${cmd_hosts}" -m "tidb" -i "${tidb_index}" -k "${ti_args}" \
			"${ti_file}" 'mysql' "${query}" "${db}" false`
			echo "current replica progress: ${current_progress}"
		fi
		sleep 1
	done

	if [ "${failed}" == 'true' ]; then
		echo "   can not reach syncing status" >&2
		return 1
	else
		echo "   available"
	fi
}

cmd_ti_wait_available "${@}"
