#!/bin/bash

function cmd_ti_schrodinger_ledger()
{
	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

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

	if [ -z "${1+x}" ] || [ -z "${1}" ]; then
		local accounts="1000000"
	else
		local accounts="${1}"
	fi

	if [ -z "${2+x}" ] || [ -z "${2}" ]; then
		local interval="2s"
	else
		local interval="${2}"
	fi

	if [ -z "${3+x}" ] || [ -z "${3}" ]; then
		local concurrency="100"
	else
		local concurrency="${3}"
	fi

	if [ -z "${4+x}" ] || [ -z "${4}" ]; then
		local pessimistic="true"
	else
		local pessimistic="${4}"
	fi

	if [ -z "${5+x}" ] || [ -z "${5}" ]; then
		local enable_async_commit="1"
	else
		local enable_async_commit="${5}"
	fi

	if [ -z "${6+x}" ] || [ -z "${6}" ]; then
		local allow_batch_cop="2"
	else
		local allow_batch_cop="${6}"
	fi

	if [ "${pessimistic}" == "true" ]; then
		"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -m "${cmd_mod_names}" \
			-i "${cmd_indexes}" -k "${ti_args}" "${ti_file}" 'mysql' "set @@global.tidb_txn_mode = 'pessimistic'"
	else
		"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -m "${cmd_mod_names}" \
			-i "${cmd_indexes}" -k "${ti_args}" "${ti_file}" 'mysql' "set @@global.tidb_txn_mode = 'optimistic'"
	fi

	"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -m "${cmd_mod_names}" -i "${cmd_indexes}" \
	  -k "${ti_args}" "${ti_file}" 'mysql' "set @@global.tidb_enable_async_commit=${enable_async_commit}"

	"${integrated}/ops/ti.sh" -h "${cmd_hosts}" -m "${cmd_mod_names}" -i "${cmd_indexes}" \
	  -k "${ti_args}" "${ti_file}" 'mysql' "set @@global.tidb_allow_batch_cop=${allow_batch_cop}"

	# wait for txn mode setting take effect
	sleep 3

	local host=`from_mod_get_host "${tidb_mod}"`
	local dir=`from_mod_get_dir "${tidb_mod}"`

	local port=`ssh_get_value_from_proc_info "${host}" "${dir}" 'tidb_port'`

	local bin_dir="/tmp/ti/master/bins"
	# TODO: remove hardcode file path
	local conf_file="${integrated}/conf/tools.kv"
	local binary_url=`cross_platform_get_value "${conf_file}" "ledger_url"`
	echo "Downloading test binary..."
	download_test_binary "${binary_url}" "ledger" "${bin_dir}"
	echo "Start to run ledger test..."
	echo "Number of accounts: ${accounts}"
	echo "Verify interval: ${interval}"
	echo "Concurrency worker count: ${concurrency}"
	echo "Use pessimistic transaction: ${pessimistic}"
	echo "Enable async commit: ${enable_async_commit}"
	echo "Allow batch cop: ${allow_batch_cop}"
	export TIDB_SERVICE="${host}:${port}"
	"${bin_dir}/ledger" \
		-accounts="${accounts}" \
		-interval="${interval}" \
		-concurrency="${concurrency}" \
		-pessimistic="${pessimistic}" \
		1>ledger.log 2>&1	
}

set -euo pipefail
cmd_ti_schrodinger_ledger "${@}"
