#!/bin/bash

# Config TiDB settings 
mysql -h ${tidb_lb} -P 4000 -u root \
-e "set global tidb_hashagg_final_concurrency=1;" \
-e "set global tidb_hashagg_partial_concurrency=1;" \
-e "set global tidb_enable_async_commit = 1;" \
-e "set global tidb_enable_1pc = 1;" \
-e "set global tidb_guarantee_linearizability = 0;" \
-e "set global tidb_enable_clustered_index = 1;" \
-e "create database sbtest;"

# install sysbench
sudo yum install epel-release -y
sudo yum install sysbench -y

# load test data
sysbench oltp_common \
    --threads=16 \
    --rand-type=uniform \
    --db-driver=mysql \
    --mysql-db=sbtest \
    --mysql-host=${tidb_lb} \
    --mysql-port=4000\
    --mysql-user=root \
    --mysql-password= \
    prepare --tables=16 --table-size=10000000

# analyze tables
for db in {1..16}
do
    echo "analyzing table sbtest$db"
    mysql -h ${tidb_lb} -P 4000 -u root \
    -e "analyze table sbtest.sbtest$db"
done

# backup test data to s3
/home/centos/.tiup/bin/tiup br backup db \
    --db sbtest \
    --pd ${dashboard_ip}:2379 \
    --storage "s3://${s3_bucket}/sysbench_backup" \
    --s3.region "${region}" \
    --send-credentials-to-tikv=false \
    --log-file backuptable.log 

# create result file
touch sysbench_result

# run tests
TESTS="oltp_point_select oltp_update_index oltp_update_non_index oltp_read_write"
for testname in $TESTS
do
    for threads in 150 700
    do
        echo "############### SYSBENCH test   testname: $testname, thread number: $threads " >> sysbench_result
        # run test
        sysbench $testname \
            --threads=$threads \
            --time=300 \
            --report-interval=1 \
            --rand-type=uniform \
            --db-driver=mysql \
            --mysql-db=sbtest \
            --mysql-host=${tidb_lb} \
            --mysql-port=4000 \
            --mysql-user=root \
            run --tables=16 --table-size=10000000 | grep -v '] thds:' | tee -a sysbench_result

        # drop database
        mysql -h ${tidb_lb} -P 4000 -u root -e "drop database sbtest;"

        # restore test data
        /home/centos/.tiup/bin/tiup br restore db \
            --db sbtest \
            --pd ${dashboard_ip}:2379 \
            --storage "s3://${s3_bucket}/sysbench_backup" \
            --s3.region "${region}" \
            --send-credentials-to-tikv=false \
            --log-file backuptable.log 
    done
done

# cleanup test data from tidb database
mysql -h ${tidb_lb} -P 4000 -u root -e "drop database sbtest;"


# cleanup backup data in s3
aws s3 rm --recursive s3://${s3_bucket}/sysbench_backup
