#!/bin/sh
#
# Copyright (C) 2000-2026 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run four concurrent jobs and then cancel 2 of them
#

TestName="cancel-multiple-jobs-test"
JobName=concurrent-jobs
. scripts/functions

copy_test_confs

echo "${cwd}/tmp/largefile" >${cwd}/tmp/file-list
if test -c /dev/urandom ; then
# Create 56MB file with random data
#  echo "Creating a 56MB file with random data ..."
   dd if=/dev/urandom of=${cwd}/tmp/largefile bs=1024 count=55000 >/dev/null 2>&1
else
#  echo "Creating a 56MB file with bacula-dir data ..."
   dd if=$bin/bacula-dir of=${cwd}/tmp/1 bs=1024 count=1000 >/dev/null 2>&1
   cat ${cwd}/tmp/1 ${cwd}/tmp/1 ${cwd}/tmp/1 ${cwd}/tmp/1 ${cwd}/tmp/1 >${cwd}/tmp/2
   rm -f ${cwd}/tmp/1
   cat ${cwd}/tmp/2 ${cwd}/tmp/2 ${cwd}/tmp/2 ${cwd}/tmp/2 ${cwd}/tmp/2 >>${cwd}/tmp/3
   rm -f ${cwd}/tmp/2
   cat ${cwd}/tmp/3 ${cwd}/tmp/3 ${cwd}/tmp/3 ${cwd}/tmp/3 ${cwd}/tmp/3 >${cwd}/tmp/largefile
   rm -f ${cwd}/tmp/3
fi 

#echo "largefile created"

# Add some jobs and fileset for this test
cat <<EOF >>${cwd}/bin/bacula-dir.conf
JobDefs {
  Name = "DefaultJob"
  Type = Backup
  Client=${HOST}-fd 
  FileSet="Full Set"
  Storage = File
  Messages = Standard
  Pool = Default
  Maximum Concurrent Jobs = 10
  SpoolData=yes
  Max Run Time = 30min
  Reschedule On Error = no
  Reschedule Interval = 10
  Reschedule Times = 1
}
Job {
  Name = RUN4
  ClientRunBeforeJob="sleep 20"
  RunScript {
    Command = "sleep 20"
    RunsWhen = After
  }
  JobDefs = DefaultJob
}
EOF


change_jobname CompressedTest $JobName
start_test
     
cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
@$out  ${cwd}/tmp/log1.out
label storage=File volume=TestVolume001
run job=RUN4 level=Full yes
run job=RUN4 level=Full yes
run job=RUN4 level=Full yes
run job=RUN4 level=Full yes
cancel
1,3
yes
wait
messages
@# 
@# now do a restore
@#
@$out   ${cwd}/tmp/log2.out
restore where=${cwd}/tmp/bacula-restores select storage=File
unmark *
mark *
done
yes
wait
messages
@$out $tmp/log3.out
run job=RUN4 level=Full yes
@# it will cancel the jobid 6 even if jobid 1 is requested
cancel jobid=1 yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File
stop_bacula

check_two_logs
diff ${cwd}/tmp/largefile  ${cwd}/tmp/bacula-restores${cwd}/tmp/largefile 2>&1 >/dev/null
dstat=$?

grep "Backup Canceled" $tmp/log3.out > /dev/null
if [ $? -eq 0 ]; then
    print_debug "ERROR: 'cancel jobid=1 yes' command should not cancel an other job"
    estat=1
fi


end_test
