#!/bin/bash
source ../_helper.sh

echo compatibletest start
rm -rf ./compatibletest_pd
rm -rf ./compatibletest_tikv
rm -rf ./out
rm -rf ./pd.log ./tidb.log ./tikv.log
rm -rf ./compatible_test


prepare_env "tidb" "tidb-test"

echo $GOPATH

go build

#TODO add all env variable back at tidb-test
recover_env

if [ ! -x $NEW_BINARY ]; then
    echo NEW_BIANRY:$NEW_BINARY does not exists or is not an excutable file
    exit 1
fi

if [ "${UPGRADE_PART}" = "tikv" ]; then
    TIKV_PATH=$OLD_BINARY
elif [ "${UPGRADE_PART}" = "pd" ]; then 
    PD_PATH=$OLD_BINARY
elif [ "${UPGRADE_PART}" = "tidb" ]; then
    TIDB_PATH=$OLD_BINARY
fi

if [ ! -x $PD_PATH ]; then
    echo PD_PATH:$PD_PATH does not exists or is not an excutable file
    exit 1
fi
$PD_PATH --data-dir=compatibletest_pd \
         --log-file=pd.log &>out &
PD_PID=$!

sleep 8

if [ ! -x $TIKV_PATH ]; then
    echo PD_PATH:$TIKV_PATH does not exists or is not an excutable file
    exit 1
fi
$TIKV_PATH --pd="127.0.0.1:2379" \
           --addr="127.0.0.1:20160" \
           --data-dir=compatibletest_tikv \
           --log-file=tikv.log &>out &
TIKV_PID=$!

sleep 8

if [ ! -x $TIDB_PATH ]; then
    echo PD_PATH:$TIDB_PATH does not exists or is not an excutable file
    exit 1
fi
$TIDB_PATH --store=tikv \
           --path="127.0.0.1:2379" \
           --socket="" \
           --log-file=tidb.log &>out &
TIDB_PID=$!

sleep 8

./compatible_test -phase old
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo "compatibletest check old failed"
    exit 1
fi

if [ "${UPGRADE_PART}" = "tikv" ]; then
    kill $TIKV_PID
    wait $TIKV_PID
    TIKV_PATH=$NEW_BINARY
    $TIKV_PATH --pd="127.0.0.1:2379" \
               --addr="127.0.0.1:20160" \
               --data-dir=compatibletest_tikv \
               --log-file=tikv.log &>out &
elif [ "${UPGRADE_PART}" = "pd" ]; then 
    kill $PD_PID
    wait $PD_PID
    PD_PATH=$NEW_BINARY
    $PD_PATH --data-dir=compatibletest_pd \
             --log-file=pd.log &>out &
elif [ "${UPGRADE_PART}" = "tidb" ]; then
    kill $TIDB_PID
    wait $TIDB_PID
    TIDB_PATH=$NEW_BINARY
    $TIDB_PATH --store=tikv \
               --path="127.0.0.1:2379" \
               --socket="" \
               --log-file=tidb.log &>out &
fi

sleep 8

./compatible_test -phase new
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo "compatibletest check new failed"
    exit 1
fi

echo compatibletest check successful!
exit 0
