#!/bin/bash
set -e
set -o pipefail
set -u
#
# Run a first job that has a runscript BEFORE,
# then run a second job while the first is executing the script.
# First job should not be reserving a device while in RunScript Before
# The second job should not wait for the first to reserve a device.
#
TestName="$(basename "$(pwd)")"
export TestName

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

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

start_test

sleeping_job="runscriptjob"
regular_job="backup-bareos-fd"
reservationlog="$tmp/reservation-order.out"
querylog="$tmp/reservation-query.out"

rm -f $reservationlog

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
messages
@$out $reservationlog
run job=${sleeping_job} level=Full yes
@sleep 3
run job=${regular_job} storage=File2 level=Full yes
wait job=${regular_job}
wait
messages
END_OF_DATA

run_bconsole

sleepjob_id=$(awk '/Job queued./{i++}i==1 {print; exit;}' "$reservationlog" | sed -n -e 's/^.*JobId=//p')
regularjob_id=$(awk '/Job queued./{i++}i==2 {print; exit;}' "$reservationlog" | sed -n -e 's/^.*JobId=//p')

# this query will return _something_ when the regular job _did not_ wait
# and nothing if it _did_ wait.
cat <<END_OF_DATA >"$tmp/bconcmds"
@$out $querylog
sqlquery
SELECT regular.starttime, regular.endtime, sleep.starttime, sleep.endtime
FROM job regular, job sleep
WHERE regular.jobid=${regularjob_id}
  AND sleep.jobid=${sleepjob_id}
  AND regular.endtime <= sleep.endtime;
END_OF_DATA

run_bconsole

expect_not_grep "No results to list" \
  "$querylog" \
  "The regular job had to wait for the sleepy job!"

expect_grep "JobId $regularjob_id: Using Device \"FileStorage2\" to write." \
  "$reservationlog" \
  "Regular job did not reserve the device while sleeping job was sleeping!"

expect_grep "JobStatus=OK" \
  "$reservationlog" \
  "Regular job did not finish correctly"

end_test
