#!/bin/bash

# set basic env
source ../_helper.sh
TIDB_SERVER_EXEC="./jdbctest_tidb-server"

# 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_EXEC} 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 test start"

FAST_TIDB_LOG="fast_tidb.log"
SLOW_TIDB_LOG="slow_tidb.log"

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

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

# start test
mvn '-Dtest=!Statement*, !ResultSet*' '-DTIDBPORT=4001' test > fast_cases.log 2>&1 &
FAST_PID=$!
mvn '-Dtest=Statement*, ResultSet*' '-DTIDBPORT=4002' test > slow_cases.log 2>&1 &
SLOW_PID=$!
wait $FAST_PID
FAST_EXIT_CODE=$?
wait $SLOW_PID
SLOW_EXIT_CODE=$?

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


# handle race
RACE_RET=`grep 'DATA RACE' ${FAST_TIDB_LOG} || true`
if [ -n "${RACE_RET}" ]
then
	echo "tidb-server DATA RACE!"
	cat ${FAST_TIDB_LOG}
	exit 1
fi
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

echo "jdbc test finish"
exit 0
