#!/bin/bash
set +x
# set basic env
source ../_helper.sh

# set optional env by some options
while getopts "bs:v:" o
do
	case $o in
		b)
			# build a new server binary
			echo "building tidb-server binary: ${TIDB_SERVER_EXEC}"
			prepare_env "tidb" "no need for tidb-test"
			go build -race -o ${TIDB_SERVER_PATH} github.com/pingcap/tidb/tidb-server
			recover_env
			;;
		s)
			# set an exist server binary
			TIDB_SERVER_EXEC="$OPTARG"
			;;
		v)
			# set the vendor
			GOPATH="$OPTARG:$GOPATH"
			echo "GOPATH: $GOPATH"
			;;
		*)
			# unknown option flag
			echo "unknown argument flag"
			exit 1
			;;
	esac
done

echo "jdbc slow test start"

SLOW_TIDB_LOG="slow_tidb.log"

# start tidb servers
echo "starting tidb-servers, log file: ${SLOW_TIDB_LOG}"
${TIDB_SERVER_PATH} -config slow_config.toml -store unistore -path "" -lease 0s > ${SLOW_TIDB_LOG} 2>&1 &
SLOW_SERVER_PID=$!
sleep 5
echo "tidb-server(PID: ${SLOW_SERVER_PID}) started"

echo "loading init file"
unset GOPATH
unset GOROOT
GOPATH=`realpath ../../../../..` SERVER="root@tcp(127.0.0.1:4002)/" go run init.go

# start test
mvn '-Dtest=Statement*, ResultSet*' '-DTIDBPORT=4002' test
EXIT_CODE=$?

# handle test results
if [ ${EXIT_CODE} -ne 0 ]
then
	echo "ERROR: jdbc test failed!"
	echo "=========== ERROR EXIT [${EXIT_CODE}]: FULL tidb.log BEGIN ============"
	cat ${SLOW_TIDB_LOG}
	echo "=========== ERROR EXIT [${EXIT_CODE}]: FULL tidb.log END =============="
	exit 1
fi

# handle race
RACE_RET=`grep 'DATA RACE' ${SLOW_TIDB_LOG} || true`
if [ -n "${RACE_RET}" ]
then
	echo "tidb-server DATA RACE!"
	cat ${SLOW_TIDB_LOG}
	exit 1
fi
