#!/bin/bash

function cmd_ti_store_rm()
{
	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 tiflash_index_arg='random'
	if [ ! -z "${1+x}" ] && [ ! -z "${1}" ]; then
		local tiflash_index_arg="${1}"
	fi

	if [ "${tiflash_index_arg}" == 'random' ]; then
		local tiflash_index=`from_mods_random_mod "${mods}" 'tiflash'`
		if [ -z "${tiflash_index}" ]; then
			echo "[cmd store/rm] no selected tiflash" >&2
			return 1
		fi
	else
		local tiflash_index="${tiflash_index_arg}"
	fi

	local ti="${integrated}/ops/ti.sh"

	local tiflash_prop=`"${ti}" -h "${cmd_hosts}" -i "${tiflash_index}" -m 'tiflash' -k "${ti_args}" "${ti_file}" 'prop'`
	local tiflash_host=`echo "${tiflash_prop}" | grep "listen_host" | awk -F 'listen_host:' '{print $2}' | tr -d ' '`
	local tiflash_proxy_port=`echo "${tiflash_prop}" | grep "proxy_port" | awk -F 'proxy_port:' '{print $2}' | tr -d ' '`

	local store_addr="${tiflash_host}:${tiflash_proxy_port}"
	local store_id=`"${integrated}/ops/ti.sh" -k "${ti_args}" "${ti_file}" "pd/ctl_raw" "store" | \
		print_jpath "$.stores[?(@.store.peer_address=='${store_addr}')].store.id"`
	if [ -z "${store_id}" ]; then
		echo "[cmd store/rm] cannot get store id from pd by ${store_addr}" >&2
		return 1
	fi

	echo "=> learner store address: ${store_addr}, id: ${store_id}, tiflash: ${tiflash_index}. removing"

	#"${ti}" -h "${cmd_hosts}" -i "${tiflash_index}" -m 'tiflash' -k "${ti_args}" "${ti_file}" 'fstop'

	local op_resp=`"${integrated}/ops/ti.sh" -k "${ti_args}" "${ti_file}" \
		"pd/ctl_raw" "store delete ${store_id}"`
	# TODO: remove tr
	# local op_resp=`echo "${op_resp}" | tr -d '\[\][0-9] \.'`
	if [ "${op_resp}" != "Success!" ]; then
		echo "[cmd store/rm] remove store ${store_addr} failed: ${op_resp}"
		return 1
	fi

	local failed='true'
	for (( r = 0; 0 == 0; r++ )); do
		local status=`"${ti}" -h "${cmd_hosts}" -i "${tiflash_index}" -m 'tiflash' -k "${ti_args}" \
			"${ti_file}" 'store/status' | awk '{print $3}'`
		if [ "${status}" == "Empty" ]; then
			local failed='false'
			break
		fi
		if [ $((${r} % 10)) = 0 ] && [ ${r} -ge 10 ]; then
			echo "   #${r} waiting for store ${store_addr} deleted, current status: ${status}"
		fi
		sleep 1
	done

	if [ "${failed}" == 'true' ]; then
		echo "   cant not reach Tombstone status"
		return 1
	fi

	"${ti}" -h "${cmd_hosts}" -i "${tiflash_index}" -m 'tiflash' -k "${ti_args}" "${ti_file}" 'burn'

	echo "=> learner store address: ${store_addr}, id: ${store_id}, tiflash: ${tiflash_index}. removed"
	echo "   OK"
}

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