#!/bin/bash
# parameter 1: sql
# parameter 2: database host
# parameter 3: database port
# parameter 4: other mysql client settings

set -e

sql=${1}

host=127.0.0.1
if [ $# -gt 1 ]; then
	shift
	host=${1}
fi

port=4000
if [ $# -gt 1 ]; then
	shift
	port=${1}
fi

if [ $# -gt 1 ]; then
	shift
	other=${*}
fi

prepare="set global tidb_enable_clustered_index = 'int_only';"

# Check if OUT_DIR contains TEST_NAME, if so, truncate OUT_DIR to the parent directory
ADJUSTED_OUT_DIR="$OUT_DIR"
if [ -n "$TEST_NAME" ] && [[ "$OUT_DIR" == *"/$TEST_NAME"* ]]; then
	ADJUSTED_OUT_DIR="${OUT_DIR%/$TEST_NAME}"
fi

log_file="$ADJUSTED_OUT_DIR/$TEST_NAME/sql_res.$TEST_NAME.log"
remainLogFile="$ADJUSTED_OUT_DIR/$TEST_NAME/sql_res.$TEST_NAME.remain.log"

log_with_timestamp() {
	# Clear the log file at the start of each command
	while IFS= read -r line; do
		echo "[$(date)] $line" >>"$remainLogFile"
	done
}

echo "[$(date)] Executing SQL: ${sql}" >"$log_file"
echo "[$(date)] Executing SQL: ${sql}" >>"$remainLogFile"

mysql -uroot -h${host} -P${port} ${other} --default-character-set utf8mb4 -E -e "${prepare}" 2>&1 | tee "$log_file" | log_with_timestamp

mysql -uroot -h${host} -P${port} ${other} --default-character-set utf8mb4 -E -e "${sql}" 2>&1 | tee "$log_file" | log_with_timestamp
