#!/bin/sh
#
#  Test bug 897
#

TestName="bug-897"
JobName=backup

. scripts/functions
copy_test_confs

rm -f bin/bareos-dir.conf
rm -f ${cwd}/tmp/RUN*log
rm -f ${cwd}/tmp/fifo
rm -f ${cwd}/tmp/RUN_BUG_897
rm -f ${cwd}/tmp/RUN_FD_FAILED

/bin/cp -f scripts/bareos-dir.conf.testrunscript bin/bareos-dir.conf

# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data data/small.tgz

# the default fileset FS_TESTJOB backups all file and directories defined in "${tmp}/file-list".
echo "${BackupDirectory}" >${tmp}/file-list
echo "${tmp}/fifo" >> ${tmp}/file-list
mkfifo "${tmp}/fifo"

# use this to be able to cancel a running job
(
  cat > ${tmp}/fifo < /dev/zero
  cat > ${tmp}/fifo < /dev/zero
) &

start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
label volume=TestVolume001
@$out ${cwd}/tmp/RUN_FD_FAILED.log
run job=RUN_FD_FAILED yes
wait
messages
@sleep 1
@$out ${cwd}/tmp/RUN_BUG_897.log
setdebug level=200 client=$CLIENT
run job=BUG_897 yes
@sleep 2
cancel
yes
wait
messages
st dir
quit
END_OF_DATA

run_bareos
check_for_zombie_jobs storage=File
stop_bareos

dstat=0
bstat=0
rstat=0
export dstat
export bstat
export rstat

grep 'fd: ClientBeforeJob: run command "/bin/false RUN_FD_FAILED1"' ${cwd}/tmp/RUN_FD_FAILED.log >/dev/null 2>&1
a=$?
grep 'fd: ClientBeforeJob: run command "/bin/false RUN_FD_FAILED2"' ${cwd}/tmp/RUN_FD_FAILED.log >/dev/null 2>&1
b=$?
grep 'dir: AfterJob: run command "/bin/echo RunAfterFailedJob"' ${cwd}/tmp/RUN_FD_FAILED.log >/dev/null 2>&1
c=$?
grep 'touching' ${cwd}/tmp/RUN_FD_FAILED.log >/dev/null 2>&1
d=$?
grep '*** Backup Error ***' ${cwd}/tmp/RUN_FD_FAILED.log >/dev/null 2>&1
e=$?
if [ $a = 0 -a $b = 0 -a $c = 0 -a $d = 0 -a $e = 0 ]
then
   [ "$debug" = 1 ] && echo RUN_FD_FAILED ok
else
   echo "RUN_FD_FAILED in error"
   rstat=1
fi
if test -f ${cwd}/tmp/RUN_FD_FAILED
then
    echo "The ${cwd}/tmp/RUN_FD_FAILED have been created, but nothing could be found"
    echo "in the log"
fi


grep 'touching' ${cwd}/tmp/RUN_BUG_897.log >/dev/null 2>&1
d=$?
if [ $d = 0 ]
then
   [ "$debug" = 1 ] && echo RUN_FD_FAILED ok
else
   echo "RUN_BUG_897 in error"
   rstat=1
fi
if test -f ${cwd}/tmp/RUN_BUG_897
then
    echo "The ${cwd}/tmp/RUN_BUG_897 have been created, but nothing could be found"
    echo "in the log"
fi



end_test
