#!/bin/bash
set -eo pipefail

dir="$(dirname "$(realpath "$BASH_SOURCE")")"

image="$1"

export MYSQL_ROOT_PASSWORD='this is an example test password'
export MYSQL_USER='0123456789012345' # "ERROR: 1470  String 'my cool mysql user' is too long for user name (should be no longer than 16)"
export MYSQL_PASSWORD='my cool mysql password'
export MYSQL_DATABASE='my cool mysql database'

cname="mysql-container-$RANDOM-$RANDOM"
cid="$(
	docker run -d \
		-e MYSQL_ROOT_PASSWORD \
		-e MYSQL_USER \
		-e MYSQL_PASSWORD \
		-e MYSQL_DATABASE \
		--name "$cname" \
		"$image"
)"
trap "docker rm -vf $cid > /dev/null" EXIT

mysql() {
	docker run --rm -i \
		--link "$cname":mysql \
		--entrypoint mysql \
		-e MYSQL_PWD="$MYSQL_PASSWORD" \
		"$image" \
		-hmysql \
		-u"$MYSQL_USER" \
		--silent \
		"$@" \
		"$MYSQL_DATABASE"
}

. "$dir/../../retry.sh" --tries 20 "echo 'SELECT 1' | mysql"

echo 'CREATE TABLE test (a INT PRIMARY KEY, b INT, c VARCHAR(255))' | mysql
[ "$(echo 'SELECT COUNT(*) FROM test' | mysql)" = 0 ]
echo 'INSERT INTO test VALUES (1, 2, "hello")' | mysql
[ "$(echo 'SELECT COUNT(*) FROM test' | mysql)" = 1 ]
echo 'INSERT INTO test VALUES (2, 3, "goodbye!")' | mysql
[ "$(echo 'SELECT COUNT(*) FROM test' | mysql)" = 2 ]
echo 'DELETE FROM test WHERE a = 1' | mysql
[ "$(echo 'SELECT COUNT(*) FROM test' | mysql)" = 1 ]
[ "$(echo 'SELECT c FROM test' | mysql)" = 'goodbye!' ]
echo 'DROP TABLE test' | mysql

# resolving should be disabled by default for PS
if [[ "$image" != *xtradb* ]]; then
	[ "$(echo 'SELECT @@GLOBAL.skip_name_resolve' | mysql)" = '1' ]
fi
# tzinfo should be imported by default
[ "$(echo "SELECT CONVERT_TZ('2018-01-01 00:00:00', 'US/Eastern', 'US/Central');" | mysql)" = '2017-12-31 23:00:00' ]
# certificates should be generated by default
docker exec "$cname" bash -c "
	if [ ! -f /usr/bin/mysql_ssl_rsa_setup ]; then
		echo warning: no ssl support
		exit 0
	fi
	if [ ! -f /var/lib/mysql/private_key.pem ]; then
		exit 1
	fi
"
