#!/bin/bash

#TODO check with sre team, all env variable should be present
echo gormtest start
cd gorm
rm -rf ./gormtest_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 gorm_test_tidb-server github.com/pingcap/tidb/tidb-server
    TIDB_SERVER_PATH=./gorm_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

echo "$PWD"
save_pwd="$PWD"

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 -store=unistore --path="" &>tidb.log &
fi
SERVER_PID=$!

sleep 10
cd tests || exit
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 || true

echo gormtest end

cd "$save_pwd" || exit
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 ============"
    echo "cat tidb.log"
    cat tidb.log
    echo "=========== ERROR EXIT [${EXIT_CODE}]: FULL tidb.log END =============="
fi
exit $EXIT_CODE
