#!/bin/bash

#TODO check with sre team, all env variable should be present
echo beego_orm_test start
cd beego/client/orm
rm -rf ./orm_test_tidb-server
rm -rf ./tidb*.log
rm -rf ./data

echo `pwd`

if [[ -z "${TIDB_SERVER_PATH}" || ! -e ${TIDB_SERVER_PATH} ]]; then
    echo -e "no tidb-server was found, build from source code"
    # This is likely to be failed, depending on whether tidb parser is well set up
    GO111MODULE=on go build -o orm_test_tidb-server github.com/pingcap/tidb/tidb-server
    TIDB_SERVER_PATH=./orm_test_tidb-server
fi

if [[ -z "${TIDB_CONFIG}" || ! -e ${TIDB_CONFIG} ]]; then
    TIDB_CONFIG="../../../config.toml"
fi

echo "go path is $GOPATH"

GO111MODULE=on go build

if [ "${TIDB_TEST_STORE_NAME}" = "tikv" ]; then
    ${TIDB_SERVER_PATH} -config $TIDB_CONFIG -lease 0 -store tikv -path "${TIKV_PATH}" &>tidb.log &
else
    ${TIDB_SERVER_PATH} -config $TIDB_CONFIG -lease 0 -store=unistore --path="" &>tidb.log &
fi
SERVER_PID=$!

sleep 10

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

sleep 1

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

kill -9 $SERVER_PID || true

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