#!/bin/bash

function ti_cmd_tpch_load_no_raft
{
	local index="${1}"
	local mod_name="${2}"
	local dir="${3}"
	local conf_rel_path="${4}"
	local host="${5}"

	shift 5

	if [ "${mod_name}" != 'tiflash' ]; then
		return
	fi

	# TODO: load to multiple tiflash instances
	if [ "${index}" != '0' ]; then
		return
	fi

	if [ -z "${3+x}" ]; then
		echo "[cmd tpch/load_no_raft] usage: <cmd> scale table(all|lineitem|...) engine(tmt|dt|mt) [data_dir={integrated}/data/tpch] [threads=4]" >&2
		return
	fi

	local scale="${1}"
	local table="${2}"
	local engine="${3}"

	if [ ! -z "${4+x}" ] && [ ! -z "${4}" ]; then
		local data_dir="${4}"
	else
		local data_dir="${integrated}/data/tpch"
	fi

	# blocks == threads
	if [ ! -z "${5+x}" ] && [ ! -z "${5}" ]; then
		local blocks="${5}"
	else
		local blocks='4'
	fi

	local schema_dir="${integrated}/resource/tpch/ch/schema/${engine}"

	local db=`echo "tpch_${scale}_${engine}_no_raft" | tr '.' '_'`

	if [ "${table}" != 'all' ]; then
		local tables=("${table}")
	else
		local tables=(nation customer orders part region supplier partsupp lineitem)
	fi

	local file="${integrated}/conf/tools.kv"
	local ch_bin="${dir}/tiflash/tiflash"
	local port=`ssh_get_value_from_proc_info "${host}" "${dir}" 'tcp_port'`

	for table in ${tables[@]}; do
		local table_dir="${data_dir}/tpch_s`echo ${scale} | tr '.' '_'`_b${blocks}/${table}"
		local start_time=`date +%s`
		echo "=> [$host] loading ${db}.${table} to CH directly"
		generate_tpch_data "${table_dir}" "${scale}" "${table}" "${blocks}"
		echo '   generated'
		load_tpch_data_to_ch "${ch_bin}" "${host}" "${port}" "${schema_dir}" "${table_dir}" "${db}" "${table}"
		local finish_time=`date +%s`
		local duration=$((finish_time-start_time))
		echo "   loaded in ${duration}s"
	done
}

set -euo pipefail
ti_cmd_tpch_load_no_raft "${@}"
