#!/bin/bash

function cmd_ti_wait_table()
{
	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/table] usage: <cmd> database table [timeout=1200]" >&2
		return 1
	fi

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

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

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

	echo "=> wait for ${db}.${table} exists"

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

	local failed='true'
	for (( i = 0; i < "${timeout}"; i++ )); do
		local has_db=`"${ti}" -h "${cmd_hosts}" -m "${cmd_mod_names}" -i "${cmd_indexes}" -k "${ti_args}" \
			"${ti_file}" 'ch' 'show databases' 2>/dev/null | trim_host | grep "^${db}$"`
		if [ ${?} == 0 ] && [ ! -z "${has_db}" ]; then
			local failed='false'
			break
		fi
		if [ $((${i} % 10)) = 0 ] && [ ${i} -ge 10 ]; then
			echo "   #${i} waiting for database ${db}"
		fi
		sleep 1
	done
	if [ "${failed}" == 'true' ]; then
		echo "   get database ${db} failed" >&2
		return 1
	else
		echo "   got database ${db}"
	fi

	for (( i = 0; i < "${timeout}"; i++ )); do
		local has_db=`"${ti}" -h "${cmd_hosts}" -m "${cmd_mod_names}" -i "${cmd_indexes}" -k "${ti_args}" \
			"${ti_file}" 'ch' 'show tables' "${db}"  2>/dev/null | trim_host | grep "^${table}$"`
		if [ ${?} == 0 ] && [ ! -z "${has_db}" ]; then
			local failed='false'
			break
		fi
		if [ $((${i} % 10)) = 0 ] && [ ${i} -ge 10 ]; then
			echo "   #${i} waiting for table ${db}.${table}"
		fi
		sleep 1
	done

	if [ "${failed}" == 'true' ]; then
		echo "   get table ${db}.${table} failed" >&2
		return 1
	else
		echo "   got table ${db}.${table}"
	fi
}

cmd_ti_wait_table "${@}"
