#!/bin/sh
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run a simple backup of the Bacula build directory
# Then stop the SD, corrupt the volume by adding few
# bytes at the end, and run a set of new jobs.
#
# bscan the volume 

TestName="bscan-on-error-test"
JobName=bscan
. scripts/functions

scripts/cleanup
scripts/copy-test-confs
echo "${cwd}/build" >tmp/file-list

change_jobname NightlySave $JobName
start_test

cat <<END_OF_DATA >tmp/bconcmds
@$out /dev/null
messages
@$out tmp/log1.out
label storage=File1
TestVolume001
run job=$JobName storage=File1
yes
wait
sql
select * from JobMedia;

messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1
$bin/bacula-ctl-sd stop

print_debug "Corrupting the volume..."
echo "BB02" >> $tmp/TestVolume001

$bin/bacula-ctl-sd start

cat <<END_OF_DATA >tmp/bconcmds
@$out /dev/null
messages
@$out tmp/log1.out
run job=$JobName storage=File1 level=full yes
wait
sql
select * from JobMedia;

messages
purge volume=TestVolume001
quit
END_OF_DATA

run_bconsole

echo "volume=TestVolume001" >$tmp/bscan.bsr
bscan_libdbi

# If the database has a password pass it to bscan
if test "x${db_password}" = "x"; then
  PASSWD=
else
  PASSWD="-P ${db_password}"
fi

if test "$debug" -eq 1 ; then
    $bin/bscan -w working $BSCANLIBDBI -u ${db_user} -n ${db_name} $PASSWD -S -p -b $tmp/bscan.bsr -s -c $conf/bacula-sd.conf $tmp 
else
  $bin/bscan -w working $BSCANLIBDBI -u ${db_user} -n ${db_name} $PASSWD -S -r -p -v -b $tmp/bscan.bsr -s -c $conf/bacula-sd.conf $tmp >$tmp/log3.out 2>&1
fi

cat <<END_OF_DATA >tmp/bconcmds
@$out /dev/null
messages
@$out tmp/log2.out
restore where=$tmp/bacula-restores1 jobid=3 all done yes
restore where=$tmp/bacula-restores2 jobid=4 all done yes
wait
messages
quit
END_OF_DATA

$bin/bacula-ctl-sd stop
$bin/bacula-ctl-sd start -p

run_bconsole
stop_bacula

$rscripts/diff.pl -s $tmp/bacula-restores1/$cwd/build -d $cwd/build
if [ $? != 0 ]; then
    print_debug "ERROR: Unable to restore jobid 1 after bscan"
    estat=1
fi
$rscripts/diff.pl -s $tmp/bacula-restores2/$cwd/build -d $cwd/build
if [ $? != 0 ]; then
    print_debug "ERROR: Unable to restore jobid 2 after bscan"
    estat=1
fi
end_test
