#!/usr/bin/env bash
#
# Copyright (C) 2000-2021 Kern Sibbald
# Copyright (C) 2021-2026 Bacula Systems SA
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run a simple backup of the Bacula build directory
#   do bscan for disaster recovery
#
TestName="bscan-dr-test"
JobName=backup
. scripts/functions

scripts/cleanup
scripts/copy-confs

#
# Zap out any schedule in default conf file so that
#  it doesn't start during our test
#
outf="$tmp/sed_tmp"
echo "s%  Schedule =%# Schedule =%g" >${outf}
cp $scripts/bacula-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >$scripts/bacula-dir.conf

client=`$bperl -e get_client_name`
change_jobname BackupClient1 $JobName
start_test

cat <<EOF >> $conf/bacula-dir.conf
FileSet {
  Name = Test1
  Include {
    File = $cwd/build
  }
}
Job {
  Name = "backup2"
  JobDefs = "DefaultJob"
  Write Bootstrap = $working/backup2.bsr
  FileSet = Test1
}
EOF

$bperl -e 'add_attribute("$conf/bacula-dir.conf", "MaximumVolumeBytes", "50MB", "Pool")'
$bperl -e 'set_global_maximum_concurrent_jobs(10)'

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
run job=backup2 yes
run job=$JobName yes
wait
messages
@exec "touch $cwd/build/po/fr.po"
run job=$JobName yes
run job=backup2 yes
wait
messages
quit
END_OF_DATA

run_bacula

stop_bacula

$bin/drop_bacula_tables
$bin/make_bacula_tables
$bin/grant_bacula_privileges

if [ "$db_password" != "" ]; then
    pass="-P '$db_password'"
fi

$bin/bscan -b $working/$client.bsr -m -n $db_name -u $db_user $pass -s -v -w $working FileChgr1-Dev1

cat <<END_OF_DATA >$tmp/bconcmds
@$out $tmp/log2.out
restore select all done yes fileset="Full Set"  where=$tmp/bacula-restores
wait
messages
quit
END_OF_DATA

run_bacula

$bin/bscan -b $working/backup2.bsr -m -n $db_name -u $db_user $pass -s -v -w $working FileChgr1-Dev1

cat <<END_OF_DATA >$tmp/bconcmds
@$out $tmp/log2.out
restore select all done yes fileset="Test1" where=$tmp/bacula-restores2
wait
messages
quit
END_OF_DATA

run_bconsole

stop_bacula

check_two_logs

$rscripts/diff.pl -d $tmp/bacula-restores/$cwd/build -s $cwd/build

if [ $? -ne 0 ]; then
    estat=1
    print_debug "ERROR: found difference in bacula-restore"
fi

$rscripts/diff.pl -d $tmp/bacula-restores2/$cwd/build -s $cwd/build

if [ $? -ne 0 ]; then
    estat=1
    print_debug "ERROR: found difference in bacula-restore2"
fi
end_test
