#!/bin/bash
set -e

echo -e "randgen_test start\n"

TIDB_TEST_STORE_NAME=$TIDB_TEST_STORE_NAME
TIKV_PATH=$TIKV_PATH

randgen_test_log="./tidb.log"
tests=""
record=0
record_case=""
TEST_BIN_PATH=./randgen_test

if [[ ! -e ${TEST_BIN_PATH} ]]; then
    ./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 -race -o randgen_test_tidb-server github.com/pingcap/tidb/tidb-server
    TIDB_SERVER_PATH=./randgen_test_tidb-server
fi

rm -rf $randgen_test_log

echo "START tidb_server, LOG FILE: $randgen_test_log"
if [ "${TIDB_TEST_STORE_NAME}" = "tikv" ]; then
    ${TIDB_SERVER_PATH} -config config.toml -store tikv -path "${TIKV_PATH}" > $randgen_test_log 2>&1 &
    SERVER_PID=$!
else
    ${TIDB_SERVER_PATH} -config config.toml -store unistore -path "" > $randgen_test_log 2>&1 &
    SERVER_PID=$!
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

if [ $record -eq 1 ]; then
    echo "RECORD RESULT FOR CASE: \"$record_case\""
    ${TEST_BIN_PATH} --record $record_case --log-level=error --port=4001
else
    if [ -z "$tests" ]; then
        echo "RUN ALL RANDGEN TEST CASES"
    else
        echo "RUN RANDGEN TEST CASE: $tests"
    fi
    ${TEST_BIN_PATH} --log-level=error --port=4001 $tests
fi

kill -9 $SERVER_PID || true

race=`grep 'DATA RACE' $randgen_test_log || true`
if [ ! -z "$race" ]; then
    echo "tidb-server DATA RACE!"
    cat $randgen_test_log
    exit 1
fi
echo "RANDGEN TEST FINISHED SUCCESSFULLY!"
