#!/bin/bash

TestName="$(basename "$(pwd)")"
export TestName

#shellcheck source=../../environment.in
. ./environment

#shellcheck source=../../scripts/functions
. "${rscripts}"/functions

start_test

last_job_id=$(last_jobid_or_zero)

copy_admin_id=$((last_job_id + 1))
copy_work_id=$((last_job_id + 2))
copied_job_id=$((last_job_id + 3))
new_backup_id=$((last_job_id + 4))

cat <<END_OF_DATA >$tmp/bconcmds
@$out ${NULL_DEV}
messages
@$out $tmp/copy.out
run job=Copy yes
wait jobid=${copy_admin_id}
@sleep 5
messages
@$out $tmp/copy_worker_before_status.out
llist jobid=${copy_work_id}
@$out $tmp/copy.out
@exec "sh -c 'touch ${tmp}/data/weird-files/file-4'"
run job=ai-backup-bareos-fd level=Incremental yes
wait jobid=${new_backup_id}
@$out $tmp/copy_worker_before_status.out
llist jobid=${copy_work_id}
cancel jobid=${copy_work_id}
@$out $tmp/copy.out
wait
messages
@$out $tmp/copy_worker_status.out
llist jobid=${copy_work_id}
@$out $tmp/copy_incremental_status.out
llist jobid=${new_backup_id}
END_OF_DATA
run_bconsole

expect_grep "jobstatus: R" \
  "$tmp"/copy_worker_before_status.out \
  "copy job was stopped prematurely"

expect_grep "jobstatus: A" \
  "$tmp"/copy_worker_status.out \
  "copy job was not canceled after incremental"

expect_not_grep "jobstatus: A" \
  "$tmp"/copy_incremental_status.out \
  "incremental job was canceled during copy"

expect_grep "jobstatus: T" \
  "$tmp"/copy_incremental_status.out \
  "incremental job did not terminate successfully during copy"

end_test
