#!/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
#
# Test the FileEvent on error feature
#
TestName="fileerror-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

cat <<EOF >> $conf/bacula-dir.conf
Fileset {
  Name = check
  Include  {
   Options {
       CheckFileChanges = yes
   }
   File = $tmp/file
  }
}
EOF

dd if=/dev/zero of=$tmp/file count=10000 > /dev/null 2> /dev/null
$bperl -e 'add_attribute("$conf/bacula-fd.conf", "Comm Compression", "no", "FileDaemon")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "Comm Compression", "no", "Storage")'
$bperl -e 'add_attribute("$conf/bacula-dir.conf", "Comm Compression", "no", "Director")'

change_jobname BackupClient1 $JobName
start_test

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
setdebug level=4 storage=File1
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=0
setbandwidth limit=100kb/s client
run job=$JobName fileset=check yes
@sleep 5
@exec "sh -c 'cat $conf/bacula-dir.conf >> $tmp/file'"
setbandwidth limit=100000kb/s client
wait
messages
@$out $tmp/log2.out
.jlist fileevents jobid=1
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1
stop_bacula

grep '{' $tmp/log2.out | perl -MJSON -e '$j = JSON::decode_json(<>); exit (scalar(@{$j->{data}}) == 1)'

if [ $? -ne 1 ]; then
    print_debug "ERROR: Should job file event after the error"
    estat=1
fi

end_test
