#!/bin/bash

#TODO check with sre team, all env variable should be present
echo xormtest start
cd xorm
rm -rf ./xormtest_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 xorm_test_tidb-server github.com/pingcap/tidb/tidb-server
    TIDB_SERVER_PATH=./xorm_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 -store tikv -path "${TIKV_PATH}" &>tidb.log &
else
    ${TIDB_SERVER_PATH} -config $TIDB_CONFIG -store=unistore --path="" &>tidb.log &
fi
SERVER_PID=$!

sleep 10
cd integrations
go test --db=mysql --conn_str='root:@tcp(0.0.0.0:4001)/test' --ignore_select_update=true
EXIT_CODE=$?

kill -9 $SERVER_PID || true

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