#!/bin/bash
set -e

echo -e "spring-data-jdbc_test start\n"
rm -rf ./tidb*.log

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

TIDBPORT=4000

if [[ "${TIDB_TEST_STORE_NAME}" == "tikv" ]] && [[ -n "${TIKV_PATH}" ]]; then
    ${TIDB_SERVER_PATH} -config config.toml -L error -store tikv -path "${TIKV_PATH}" &>tidb.log &
else
    ${TIDB_SERVER_PATH} -P ${TIDBPORT} -status 9080  -L error -store unistore -config config.toml -path="" &>tidb.log &
fi
SERVER_PID="${SERVER_PID} ${!}"
sleep 5

set +e

# start test
mvn "-Dspring.profiles.active=mysql" "-DTIDBPORT=${TIDBPORT}" test > cases.log 2>&1
EXIT_CODE=$?

echo -e "spring-data-jdbc_test end\n"

kill -9 $SERVER_PID || true

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
