#!/bin/bash
source ../_helper.sh

echo gosqltest start
rm -rf ./gosqltest_tidb-server
rm -rf ./tidb*.log

prepare_env "tidb" "no need for tidb-test"
echo $GOPATH

if [ ! -f ./gosqltest_tidb-server ]; then
    go build -race -o gosqltest_tidb-server github.com/pingcap/tidb/tidb-server
fi

if [ "${TIDB_TEST_STORE_NAME}" = "tikv" ]; then
    ./gosqltest_tidb-server -P 4001 -status 9081 -lease 0 -store tikv -path "${TIKV_PATH}" &>tidb.log &
else
    rm -rf ./data_dir;
    ./gosqltest_tidb-server -P 4001 -status 9081 -lease 0 &>tidb.log &
fi
SERVER_PID=$!

sleep 3


cd sqltest
go test && cd mysql && MYSQL_TEST_CONCURRENT=1 MYSQL_TEST_ADDR=127.0.0.1:4001 MYSQL_TEST_DBNAME=test CGO_ENABLED=1 GO111MODULE=on go test
EXIT_CODE=$?

kill -9 $SERVER_PID

recover_env

echo gosqltest end
grep 'DATA RACE' tidb.log &>/dev/null
if [ $? -eq 0 ]
then
    echo "ERROR: DATA RACE Found!"
    grep -A 10 -B 20 'DATA RACE' tidb.log
    EXIT_CODE=-2
fi
if [ $EXIT_CODE -ne 0 ]; then
    echo "=========== ERROR EXIT [${EXIT_CODE}]: FULL tidb.log BEGIN ============"
    cat tidb.log
    echo "=========== ERROR EXIT [${EXIT_CODE}]: FULL tidb.log END =============="
fi
exit $EXIT_CODE
