#!/bin/bash

function cmd_ti_syncing_set()
{
	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}" ] || [ -z "${1}" ] || [ -z "${2}" ]; then
		echo '[cmd syncing/set] <cmd> database table [enabled=1|0]' >&2
		return 1
	fi

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

	local enabled='1'
	if [ ! -z "${3+x}" ] && [ ! -z "${3}" ]; then
		local enabled="${3}"
		if [ "${enabled}" != '0' ] && [ "${enabled}" != '1' ]; then
			echo "[cmd syncing/set] value of enabled should be 1 or 0" >&2
			return 1
		fi
	fi

	local mod=`from_mods_random_mod "${mods}" 'tidb' 'false'`
	local dir=`from_mod_get_dir "${mod}"`
	local host=`from_mod_get_host "${mod}"`

	local port=`ssh_get_value_from_proc_info "${host}" "${dir}" 'tidb_port'`
	if [ -z "${port}" ]; then
		echo "[cmd syncing/set] get port from ${host}:${dir}/proc.info failed" >&2
		return 1
	fi

	local query="alter table ${db}.${table} set tiflash replica ${enabled}"
	mysql -h "${host}" -P "${port}" -u root --database="${db}" --comments -e "${query}"

	if [ "${enabled}" == '0' ]; then
		echo "${db}.${table}: tikv -!> tiflash, rm from tiflash"
		return
	fi

	local pd_syncing_ok=''
	local ti="${integrated}/ops/ti.sh"
	for (( i = 0; i < 1200; i++ )); do
		local pd_syncing_ok=`"${ti}" -h "${cmd_hosts}" -k "${ti_args}" \
			"${ti_file}" 'syncing/show' "${db}" | grep "^    ${table}\b"`
		if [ ! -z "${pd_syncing_ok}" ]; then
			break
		fi
		sleep 1
	done

	if [ -z "${pd_syncing_ok}" ]; then
		echo "[cmd syncing/set] syncing info not found in pd" >&2
		return 1
	fi

	echo "${db}.${table}: tikv -> tiflash"
}

set -euo pipefail
cmd_ti_syncing_set "${@}"
