#!/bin/bash

function cmd_ti_schrodinger_sqllogic()
{
	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/sqllogic] no selected tidb" >&2
		return 1
	fi

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

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

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

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

	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}" "sqllogic_url"`
	echo "Downloading test binary..."
	download_test_binary "${binary_url}" "sqllogic" "${bin_dir}"
	echo "Start to run sqllogic test..."
	echo "Parallel count: ${parallel}"
	echo "Skip error: ${skip_error}"
	if [ ! -z "${test_path}" ]; then
		echo "Test path: ${test_path}"
	fi
	echo "Enable mpp: ${enable_mpp}"
	export TIDB_SERVICE="${host}:${port}"
	local args=" -parallel=${parallel} -skip-error=${skip_error} -enable-mpp=${enable_mpp}"
	if [ ! -z "${test_path}" ]; then
		local args="${args} -test-path=${test_path}"
	fi
	"${bin_dir}/sqllogic" ${args} 1>sqllogic.log 2>&1
}

set -euo pipefail
cmd_ti_schrodinger_sqllogic "${@}"
