#!/bin/bash
# parameter 1: an ALTER SQL to be executed
# parameter 2: host
# parameter 3: port
# parameter 4: password
# parameter 5: db
# parameter 6: online ddl tool, pt or gh-ost

set -eu

line=$1
host=$2
port=$3
password=$4
schema=$5
ghost_bin=${GHOST_BINARY:-gh-ost}
ptosc_bin=${PTOSC_BINARY:-pt-online-schema-change}

table=$(echo $line | cut -d " " -f3)
alter=$(echo "$line" | cut -d " " -f4-)
echo "alter: $alter"
# gh-ost check connection port whether equals to `select @@global.port`.
# if we have test MySQL in container and port mapping, these two ports
# may different. So we cheat gh-ost that we are running on aliyun rds,
# on which will disable the port check.
if [ "$6" == "gh-ost" ]; then
	$ghost_bin -version
	$ghost_bin --user=root --host=$host --port=$port --password=$password \
		--database=$schema --table=$table --alter="$alter" \
		--serve-socket-file="$TEST_DIR/gh-ost.$schema.$table.$port.sock" \
		--allow-on-master --allow-master-master --initially-drop-ghost-table \
		--initially-drop-old-table -ok-to-drop-table -aliyun-rds -execute \
		>>$TEST_DIR/gh-ost.log
elif [ "$6" == "pt" ]; then
	$ptosc_bin --version
	$ptosc_bin --user=root --host=$host --port=$port --password=$password \
		--alter="$alter" D=$schema,t=$table \
		--recursion-method=none --print --execute \
		>>$TEST_DIR/pt-osc.log
	$ptosc_bin --user=root --host=$host --port=$port --password=$password \
		--alter "COMMENT='string' CHARACTER SET='utf8mb4'" D=$schema,t=$table \
		--recursion-method=none --print --execute \
		>>$TEST_DIR/pt-osc.log
else
	mysql -uroot -h$host -P$port -p$password --default-character-set utf8 -E -e "use $schema; $line" >>"$TEST_DIR/sql_res.$TEST_NAME.txt"
fi
