#!/bin/bash
set -e
set -o pipefail
set -u

TestName=02-copy

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

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

copy_log="$tmp/copy_log.out"
query_results="$tmp/query_results.out"

start_test

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
messages
@$out $tmp/copy-summary.out
run copy
no
@$out $tmp/copy-with-next-pool-override-summary.out
run copy-with-next-pool-override
no
@$out $copy_log
label volume=TestCopyVolume001 storage=File2 pool=FullCopy
run copy yes
wait
messages
@$out $query_results
sqlquery
SELECT type FROM job WHERE jobid=4;
.
quit
END_OF_DATA

run_bconsole "$tmp/bconcmds"

expect_grep "Termination:.*Copying OK" \
  "$copy_log" \
  "Copy job did not finish well."

expect_grep "|.*C.*|" \
  "$query_results" \
  "Copy job does not have the expected type."

expect_grep "JobId 2: BeforeJob: prevjobid=\*None\* newjobid=\*None\*" \
  "$copy_log" \
  "Before runscript does not return expected previous jobid (%O) and new jobid (%N)."

expect_grep "JobId 2: AfterJob: prevjobid=\*None\* newjobid=\*None\*" \
  "$copy_log" \
  "After runscript does not return expected previous jobid (%O) and new jobid (%N)."

expect_grep "JobId 3: BeforeJob: prevjobid=1 newjobid=4" \
  "$copy_log" \
  "Before runscript does not return expected previous jobid (%O) and new jobid (%N)."

expect_grep "JobId 3: AfterJob: prevjobid=1 newjobid=4" \
  "$copy_log" \
  "After runscript does not return expected previous jobid (%O) and new jobid (%N)."

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out $query_results
prune volume=TestVolume001 yes
sqlquery
SELECT count(jobid) FROM job WHERE type='c';
SELECT type FROM job WHERE jobid=4;
.
messages
quit
END_OF_DATA

run_bconsole "$tmp/bconcmds"

expect_grep "|     1 |" \
  "$query_results" \
  "Copy jobs were not deleted appropriately after backup volume pruning."

expect_grep "|.*B.*|" \
  "$query_results" \
  "Copy job was not upgraded to backup after original backup was pruned."

check_for_zombie_jobs storage=File

# check whether next-pool directive overrides work (in job resource > in pool resource)
expect_grep "NextPool:      FullCopy" \
  "$tmp/copy-summary.out" \
  "Wrong next pool selected for job 'copy' ."

expect_grep "NextPool:      AnotherFullCopy" \
  "$tmp/copy-with-next-pool-override-summary.out" \
  "Wrong next pool selected for job 'copy-with-next-pool-override' ."

end_test
