#!/bin/bash
set -e
set -o pipefail
set -u
#
# Run a simple backup on a mysql database
#   then convert to postgresql and restore it.
#

TestName="$(basename "$(pwd)")"
export TestName

JobName=backup-bareos-fd
. ./environment
. ${scripts}/functions

. ./environment-postgresql
${scripts}/cleanup
${scripts}/setup

. ./environment-mysql
${scripts}/cleanup
${scripts}/setup


# Fill ${BackupDirectory} with data.
setup_data

echo "$conf"/bareos-fd.d  >  "$tmp/file-list-python-plugin"

start_test

#enable only mysql
rm -f "${conf}"/bareos-dir.d/catalog/postgresql.conf "${conf}"/bareos-dir.d/catalog/mysql.conf
cp "${conf}"/bareos-dir.d/catalog/mysql.conf.template "${conf}"/bareos-dir.d/catalog/mysql.conf

cat <<END_OF_DATA >$tmp/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
setdebug level=100 storage=File
label volume=TestVolume001 storage=File pool=Full catalog=mysql
run job=$JobName yes
status director
status client=bareos-fd
status storage=File
wait
messages
@$out $tmp/files.mysql
messages
list files jobid=1
END_OF_DATA

run_bareos
stop_bareos

#enable mysql and postgresql
cp "${conf}"/bareos-dir.d/catalog/postgresql.conf.template "${conf}"/bareos-dir.d/catalog/postgresql.conf

#do the database copy
"${BAREOS_DBCOPY_BINARY}" -c "${current_test_directory}"/etc/bareos mysql postgresql

#enable only postgresql
rm "${conf}"/bareos-dir.d/catalog/mysql.conf

cat <<END_OF_DATA >$tmp/bconcmds
@#
@# now do a restore on the postgresql database
@#
@$out $tmp/log2.out
wait
restore client=bareos-fd fileset=SelfTest where=$tmp/bareos-restores select all done
yes
wait
messages
@$out $tmp/files.postgresql
messages
list files jobid=1
END_OF_DATA

run_bareos
check_for_zombie_jobs storage=File client=bareos-fd
stop_bareos

check_two_logs
check_restore_diff "${BackupDirectory}"

sed -i '/Using Catalog.*/d' "${tmp}"/files.postgresql
sed -i '/Using Catalog.*/d' "${tmp}"/files.mysql

sort "${tmp}"/files.mysql -o "${tmp}"/files.mysql
sort "${tmp}"/files.postgresql -o "${tmp}"/files.postgresql

if ! diff "${tmp}"/files.mysql "${tmp}"/files.postgresql;
then
  estat=1
  echo "differences in \"list files jobid=1\" output!"
fi

end_test
