#!/bin/bash
set -e
set -o pipefail
set -u
#
# This systemtest tests the python-fd contrib plugin
# bareos_tasks.mysql
#
TestName="$(basename "$(pwd)")"
export TestName

#shellcheck source=../environment.in
. ./environment

JobName=backup-bareos-fd
test_db_name="${db_name}_test"
RESTORE_DIR="$tmp/bareos-restores/@MYSQL/"

#shellcheck source=../scripts/functions
. "${rscripts}"/functions

skip_if_root

#shellcheck source=../scripts/mysql.sh
. "${rscripts}"/mysql.sh
"${rscripts}"/cleanup
"${rscripts}"/setup

start_test

mysql_init
mysql_server_start
start_bareos

echo "create database ${test_db_name}" | $MYSQL_CLIENT
echo "CREATE TABLE test ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, data VARCHAR(100), created TIMESTAMP DEFAULT NOW())  " | $MYSQL_CLIENT "${test_db_name}"
echo "insert into test (data) VALUES ('test entry 1') " | $MYSQL_CLIENT "${test_db_name}"

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out $tmp/log1.out
run job=$JobName yes
wait
messages

status dir
llist jobs job=$JobName
END_OF_DATA

run_bconsole "$@"
check_log $tmp/log1.out

# insert data and run incremental
echo "insert into test (data) VALUES ('test entry 2') " | $MYSQL_CLIENT "${test_db_name}"

cat <<END_OF_DATA2 >"$tmp/bconcmds"
@$out $tmp/log1i.out
@# run incremental again without any new data
run job=$JobName yes
wait
messages
status dir
END_OF_DATA2

run_bconsole "$@"
check_log $tmp/log1i.out

cat <<END_OF_DATA3 >"$tmp/bconcmds"
@$out $tmp/log2.out
restore restorejob=RestoreFile client=bareos-fd fileset=bareos_tasks_mysql yes select all done
wait
messages
status dir
llist jobs job=RestoreFile
END_OF_DATA3

run_bconsole "$@"
check_log $tmp/log2.out

check_for_zombie_jobs storage=File
stop_bareos

check_two_logs

# Check if some files are restored
ls -lR "${RESTORE_DIR}"
if [ -z "$(ls -A "${RESTORE_DIR}")" ]; then
       echo "No restore data found"
       estat=1
fi

# delete database
$MYSQL_CLIENT <<< "DROP DATABASE ${test_db_name};"

if $MYSQL_CLIENT "${test_db_name}" <<< "SELECT * FROM test WHERE id=2;" 2>/dev/null; then
    echo "database ${test_db_name} should be deleted and command should fail."
    estat=2
fi

# restore db
$MYSQL_CLIENT < "${RESTORE_DIR}/dump-database-${test_db_name}.sql"

if ! $MYSQL_CLIENT "${test_db_name}" <<< "SELECT * FROM test WHERE id=2;" >/dev/null; then
    echo "test entry not found after restore"
    estat=3
fi

mysql_server_stop
stop_bareos

end_test
