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

TestName=05-migrate

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

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

log="$tmp/$TestName.log"

start_test

migration_volume="TestMigrateVolume001"
query_results="$tmp/query_results.out"

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
messages
@$out $log
label volume=TestVolume002 storage=File pool=Full
run job=backup-bareos-fd level=Full yes
run job=backup-bareos-fd level=Full yes
run job=backup-bareos-fd level=Full yes
wait
update volume=TestVolume002 volstatus=Used
messages
label volume=$migration_volume storage=File2 pool=FullCopy
run migrate yes
wait
messages
@$out $query_results
sqlquery
SELECT type from job where jobid in (11,12,13);
.
quit
END_OF_DATA

run_bconsole

expect_grep "The following 3 JobIds were chosen to be migrated: 11,12,13" \
  "$log" \
  "Expected jobs to be migrated do not match."

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

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

expect_grep "JobId 19: BeforeJob: prevjobid=13 newjobid=20" \
  "$log" \
  "Before runscript does not return expected previous jobid (%O) and new jobid (%N)."

expect_grep "JobId 19: AfterJob: prevjobid=13 newjobid=20" \
  "$log" \
  "After runscript does not return expected previous jobid (%O) and new jobid (%N)."

# 1 administrative job that spawns 3 migration jobs
if [[ $(grep -c "Termination:.*Migration OK" "$log") -ne "4" ]]; then
  echo "Not all migration jobs finished successfully."
  estat=1
fi

if [[ $(grep -c "|.*M.*|" "$query_results") -ne "3" ]]; then
  echo "Former backup jobs were not successfully converted to 'Migrated Jobs'."
  estat=2
fi

rm -f $query_results

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out $query_results
sqlquery
SELECT count(jobid) FROM job WHERE type='g';
.
update volume=$migration_volume volstatus=Used
prune volume=$migration_volume yes
sqlquery
SELECT count(jobid) FROM job WHERE type='g';
.
quit
END_OF_DATA

run_bconsole
expect_grep "|     4 |" \
  "$query_results" \
  "Number of migration admin and worker jobs not met."

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

end_test
