#!/bin/bash

echo -e "tidb_test start\n"
TIDB_TEST_STORE_NAME=$TIDB_TEST_STORE_NAME
TIKV_PATH=$TIKV_PATH
TEST_BIN_PATH=./tidb_test

tidb_test_log="./tidb.log"
tidb_config_name="./config.toml"

SERVER_PID=''

set -ex

if [[ ! -e ${TEST_BIN_PATH} ]]; then
    ../xorm_test/build.sh
fi

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 tidb_test_tidb-server github.com/pingcap/tidb/tidb-server
    TIDB_SERVER_PATH=./tidb_test_tidb-server
fi

if [[ -z "${TIDB_PARALLELISM}" ]]; then
    TIDB_PARALLELISM=8
fi

if [[ -z "${TEST_FILE}" ]]; then
    TEST_FILE="./ql.t"
fi


rm -rf ${tidb_test_log}*

echo "START tidb_server, LOG FILE: $tidb_test_log"
if [ "${TIDB_TEST_STORE_NAME}" = "tikv" ]; then
    TIDB_PARALLELISM=1
    ${TIDB_SERVER_PATH} -config $tidb_config_name -store tikv -path "${TIKV_PATH}" > $tidb_test_log 2>&1 &
    SERVER_PID=$!
else
    for i in `seq ${TIDB_PARALLELISM}`
    do
        ${TIDB_SERVER_PATH} -P $((4000+$i)) -status $((9080+$i)) -store unistore -config $tidb_config_name -path="" > ${tidb_test_log}.${i} 2>&1 &
        SERVER_PID="${SERVER_PID} ${!}"
    done
fi
echo "tidb-server(PID: $SERVER_PID) STARTED"

sleep 30

mysql -h '127.0.0.1' -P 4001   -u root -e "set @@global.tidb_txn_mode = 'pessimistic'"

sleep 5

set +x

echo "START RUNNING TIDB TEST"
${TEST_BIN_PATH} -parallel ${TIDB_PARALLELISM} -L "error" -test-file=${TEST_FILE}
EXIT_CODE=$?

echo "TIDB TEST END"

kill -9 $SERVER_PID || true

race=`grep 'DATA RACE' ${tidb_test_log}* || true`
if [ ! -z "$race" ]; then
    echo "tidb-server DATA RACE!"
    grep -A 10 -B 20 'DATA RACE' ${tidb_test_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 =============="
else
    echo "TIDB TEST FINISHED SUCCESSFULLY!"
fi

exit $EXIT_CODE
