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

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

prepare_env "tidb" "no need for tidb-test"
cd beego/client/orm
rm -rf ./orm_test_tidb-server
rm -rf ./tidb*.log
rm -rf ./data

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

sleep 3

mysql -h '127.0.0.1' -P 4000   -u root -e "create database if not exists orm_test"

sleep 3

ORM_DRIVER=mysql ORM_SOURCE='root:@tcp(0.0.0.0:4000)/orm_test?charset=utf8mb4' go test
EXIT_CODE=$?

kill -9 $SERVER_PID

echo beego_orm_test 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
