#!/bin/bash

function cmd_ti_verify_rows()
{
	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 verify/rows] usage: <cmd> database table" >&2
		return 1
	fi

	local table="${1}.${2}"
	local mapped_table=$("${integrated}/ops/ti.sh" -h "${cmd_hosts}" -k "${ti_args}" "${ti_file}" ch/mapped_table "${1}" "${2}")

	local tiflash_rows=`"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -k "${ti_args}" "${ti_file}" 'ch' \
		"select count(1) from ${mapped_table}" '' 'TabSeparated' 'false' | trim_host | awk '{sum+=$1}END{print sum}'`

	local tidb_idx=`from_mods_random_mod "${mods}" 'tidb'`
	local tikv_rows=`"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -m tidb -i "${tidb_idx}" -k \
		"${ti_args}" "${ti_file}" 'mysql/tikv' "select count(1) from ${table}" 'test' 'false' | \
		grep -v 'count' | trim_host | awk '{if ($1=="ERROR") print "E"$2; else print $0}'`

	local learner_rows=`"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -m tidb -i "${tidb_idx}" -k \
		"${ti_args}" "${ti_file}" 'mysql/learner' "select count(1) from ${table}" 'test' 'false' | \
		grep -v 'count' | trim_host | awk '{if ($1=="ERROR") print "E"$2; else print $0}'`

	if [ -z "${tiflash_rows}" ]; then
		echo "[cmd verify/rows] execute query on tiflash failed" >&2
		return 1
	fi

	if [ "${tiflash_rows}" == "${tikv_rows}" ] && [ "${learner_rows}" == "${tikv_rows}" ]; then
		local res="OK     [${table}] ${tiflash_rows}(tiflash direct)"
		echo "${res} == ${tikv_rows}(tikv) == ${learner_rows}(tiflash over tidb)"
	else
		local res="FAILED [${table}]"
		if [ "${tiflash_rows}" == "${tikv_rows}" ]; then
			res="${res} ${tiflash_rows}(tiflash direct) == ${tikv_rows}(tikv)"
		else
			res="${res} ${tiflash_rows}(tiflash direct) != ${tikv_rows}(tikv)"
		fi
		if [ "${learner_rows}" == "${tikv_rows}" ]; then
			echo "${res} == ${learner_rows}(tiflash over tidb)"
		else
			echo "${res} != ${learner_rows}(tiflash over tidb)"
		fi
	fi
}

source "`cd $(dirname ${BASH_SOURCE[0]}) && pwd`/_env.sh"
auto_error_handle
cmd_ti_verify_rows "${@}"
