#!/bin/bash
set +x

echo "tidb jdbc unique test start"

TIDB_HOST=127.0.0.1
TIDB_PORT=4000
TIDB_LOG="local_tidb_unique_jdbc.log"

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

mysql -u root -h ${TIDB_HOST} -P ${TIDB_PORT} < init.sql

# start test
mvn install:install-file -Dfile=mysql-connector-java-8.0.29-tidb-1.0.3.jar -DgroupId=io.github.lastincisor -DartifactId=mysql-connector-java -Dversion=8.0.29-tidb-1.0.3 -Dpackaging=jar
mvn "-DTIDB_PORT=${TIDB_PORT}" "-DTIDB_HOST=${TIDB_HOST}" test
EXIT_CODE=$?

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

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