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

#TODO check with sre team, all env variable should be present
echo gormtest start

prepare_env "tidb" "no need for tidb-test"
cd gorm
rm -rf ./gormtest_tidb-server
rm -rf ./tidb*.log
rm -rf ./data

go build
go build -race -o gormtest_tidb-server github.com/pingcap/tidb/tidb-server
kill_proc_by_port 10080
if [ "${TIDB_TEST_STORE_NAME}" = "tikv" ]; then
    ./gormtest_tidb-server -lease 0 -store tikv -path "${TIKV_PATH}" &>tidb.log &
else
    ./gormtest_tidb-server -store=unistore --path="" &>tidb.log &
fi
SERVER_PID=$!

sleep 3
cd tests
GORM_DIALECT=mysql GORM_DSN='root:@tcp(0.0.0.0:4000)/test?charset=utf8mb4&parseTime=True&loc=Local' go test
EXIT_CODE=$?

kill -9 $SERVER_PID

echo gormtest end

recover_env

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
