#!/bin/bash
set -e
set -o pipefail
set -u
#
# This systemtest tests the python-fd contrib plugin
# bareos_tasks.mariadb
#
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/@MARIADB/"

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

skip_if_root

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

start_test

mariadb_init
mariadb_server_start

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

cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${NULL_DEV}
messages
@$out ${tmp}/log1.out
setdebug level=200 trace=1 timestamp=1 client=bareos-fd
run job=${JobName} yes
wait
messages
status dir
wait
time
llist jobs job=${JobName}
END_OF_DATA
echo "Run first full"
run_bconsole
expect_grep "Backup OK" "${tmp}/log1.out" "Full Backup not found!"
if [ ${estat} -ne 0 ]; then
  exit ${estat}
fi

# insert data and run another job
${MARIADB_CLIENT} "${test_db_name}" <<<"insert into test (data) VALUES ('test entry 2') "

cat <<END_OF_DATA2 >"${tmp}/bconcmds"
@$out ${NULL_DEV}
messages
@$out ${tmp}/log2.out
run job=${JobName} yes
wait
messages
status dir
wait
time
llist jobs job=${JobName}
END_OF_DATA2
echo "Run second full"
run_bconsole
expect_grep "Backup OK" "${tmp}/log2.out" "Full Backup not found!"

cat <<END_OF_DATA3 >"${tmp}/bconcmds"
@$out ${NULL_DEV}
messages
@$out ${tmp}/log3.out
restore restorejob=RestoreFile client=bareos-fd fileset=bareos_tasks_mariadb yes select all done
wait
setdebug level=0 client=bareos-fd
wait
messages
status dir
wait
time
llist jobs job=RestoreFile
END_OF_DATA3
echo "Run restore job"
run_bconsole
expect_grep "Restore OK" "${tmp}/log3.out" "Restore OK not found!"

# 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
echo "drop database ${test_db_name}"
${MARIADB_CLIENT} <<<"DROP DATABASE ${test_db_name};"

if ${MARIADB_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
echo "restore database ${test_db_name}"
${MARIADB_CLIENT} <"${RESTORE_DIR}/dump-database-${test_db_name}.sql"

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

end_test
