#!/bin/bash

set -eu

CUR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
source $CUR/../_utils/test_prepare
WORK_DIR=$OUT_DIR/$TEST_NAME
CDC_BINARY=cdc.test
SINK_TYPE=$1

function run() {
	if [ "$SINK_TYPE" != "storage" ]; then
		return
	fi

	rm -rf $WORK_DIR && mkdir -p $WORK_DIR
	start_tidb_cluster --workdir $WORK_DIR
	cd $WORK_DIR
	run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY

	# Enable tidb extension to generate the commit ts.
	SINK_URI="file://$WORK_DIR/storage_test?flush-interval=5s&enable-tidb-extension=true"
	run_cdc_cli changefeed create --sink-uri="$SINK_URI" --config=$CUR/conf/changefeed.toml

	run_sql_file $CUR/data/schema.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT}
	test_update $*

	run_sql_file $CUR/data/data.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT}
	run_storage_consumer $WORK_DIR $SINK_URI $CUR/conf/changefeed.toml ""
	sleep 8
	check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml 100
}

function test_update() {
	# test update
	run_sql_file $CUR/data/update.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT}
	sleep 30

	table_dir="$WORK_DIR/storage_test/test/test_update"
	ensure 60 ls "$table_dir" | grep -v "meta"

	version_dir=$(ls $table_dir | grep -v "meta")
	date_dir=$(ls $table_dir/$version_dir)
	data_name=$(ls $table_dir/$version_dir/$date_dir | grep "csv")

	file_path=$table_dir/$version_dir/$date_dir/$data_name

	echo "start check update"
	check_equal "update" "1" "$(cat $file_path | grep 'U' | wc -l)"
	check_equal "insert" "7" "$(cat $file_path | grep 'I' | wc -l)"
	check_equal "delete" "3" "$(cat $file_path | grep 'D' | wc -l)"
}

function check_equal() {
	if [ "$2" != "$3" ]; then
		echo "TEST: [$TEST_NAME] failed on $1, $2 expected, but $3 got"
		exit 1
	fi
}

trap stop_tidb_cluster EXIT
run $*
check_logs $WORK_DIR
echo "[$(date)] <<<<<< run test case $TEST_NAME success! >>>>>>"
