#
# Copyright 2022 PingCAP, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

cur_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

wait_file_exist() {
    timeout=0
    until [ -e "$1" ]; do
        timeout=$(( $timeout + 1 ))
        if [[ $timeout -gt 100 ]]; then
            echo "timeout! maybe BR process is exited!"; exit 1;
        fi
        sleep 1
    done
}

single_point_fault() {
    type=$1
    victim=$(shuf -i 1-3 -n 1)
    echo "Will make failure($type) to store#$victim."
    case $type in
        outage)
            wait_file_exist "$hint_backup_start"
            kv_outage -d 30 -i $victim;;
        outage-after-request)
            wait_file_exist "$hint_get_backup_client"
            kv_outage -d 30 -i $victim;;
        shutdown)
            wait_file_exist "$hint_backup_start"
            kv_outage --kill -i $victim;;
        scale-out)
            wait_file_exist "$hint_backup_start"
            kv_outage --kill -i $victim
            kv_outage --scale-out -i 4;;
    esac
}

load() {
    run_sql "create database if not exists $TEST_NAME"
    go-ycsb load mysql -P $TESTS_ROOT/"$TEST_NAME"/workload -p mysql.host="$TIDB_IP" -p mysql.port="$TIDB_PORT" -p mysql.user=root -p mysql.db="$TEST_NAME"
    run_sql 'use '$TEST_NAME'; show tables'
}

check() {
    run_sql 'drop database if exists '$TEST_NAME';'
    run_br restore full -s local://"$backup_dir"
    count=$(run_sql 'select count(*) from '$TEST_NAME'.usertable;' | tail -n 1 | awk '{print $2}')
    [ "$count" -eq 20000 ]
}
