#!/bin/sh

# This script will
# - create a database
# - dump this database with mydumper and compare it with the reference
# - restore the dump to another database
# - dump that other database with mydumper and compare it with the reference
# - delete the database that were created.

set -eu

echo "pwd is $(pwd)"

# check that it outputs something sensible and doesn't error out
echo "### minimal functionality check of mydumper binary ###"
mydumper -V | grep mydumper

echo "### create a mariadb database, tables, and adding some values ###"
mysql -e 'CREATE DATABASE IF NOT EXISTS integration_test_debian;'
mysql -e 'CREATE DATABASE IF NOT EXISTS integration_test_debian2;'
mysql -e 'CREATE TABLE itd (id INT AUTO_INCREMENT, words VARCHAR(50), PRIMARY KEY (id));' integration_test_debian
mysql -e 'INSERT INTO itd (words) VALUES ("foo"), ("bar"), ("baz");' integration_test_debian

echo "\n\n### Dump the database we just created ###"
mydumper --database integration_test_debian -v 3 2>&1

# find the latest dump file of the database created above
DUMPFILE=$(ls -1t ./*/integration_test_debian.itd.sql | head -n 1)
echo "dumpfile is located at ${DUMPFILE}."

echo "\n\n### Ensure the dumped database is identical with the reference ###"
diff -urN ./debian/tests/integration_test_debian.itd.sql "${DUMPFILE}"
echo "./debian/tests/integration_test_debian.itd.sql and ${DUMPFILE} match."

myloader --database integration_test_debian2 --directory $(ls -1td ./export-* | head -n 1)

echo '\n\n### sleep for 2 seconds to make sure the export dir increments ###'
sleep 2

echo "\n\n### Dump the new database we just restored ###"
mydumper --database integration_test_debian2 -v 3 2>&1

# find the latest dump file of the database created above
DUMPFILE=$(ls -1t ./*/integration_test_debian2.itd.sql | head -n 1)
echo "dumpfile is located at ${DUMPFILE}."

echo "\n\n### Ensure the dumped database is identical with the reference ###"
diff -urN ./debian/tests/integration_test_debian.itd.sql "${DUMPFILE}"
echo "./debian/tests/integration_test_debian.itd.sql and ${DUMPFILE} match."

echo "\n\n### Cleaning up databases ###"
mysql -e 'drop database integration_test_debian;'
mysql -e 'drop database integration_test_debian2;'
