#!/bin/bash

#   BAREOS® - Backup Archiving REcovery Open Sourced
#
#   Copyright (C) 2026-2026 Bareos GmbH & Co. KG
#
#   This program is Free Software; you can redistribute it and/or
#   modify it under the terms of version three of the GNU Affero General Public
#   License as published by the Free Software Foundation and included
#   in the file LICENSE.
#
#   This program is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
#   Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
#   02110-1301, USA.

set -e
set -o pipefail
set -u

#
# run backups on both two-drive robots in parallel
#

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

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

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

cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/parallel.out
run job=${NDMPCLIENT}-native level=Full pool=ndmp-tape storage=ndmjob yes
run job=${NDMPCLIENT}-native level=Full pool=ndmp-tape-robot2 storage=ndmjob-robot2 yes
wait
messages
END_OF_DATA

run_bconsole "${tmp}/bconcmds"

mapfile -t jobids < <(
  sed -n 's/^.*Job queued\. JobId=//p' "${log_home}/parallel.out"
)
if [ "${#jobids[@]}" -ne 2 ]; then
  set_error "expected two queued NDMP jobs, got ${#jobids[@]}"
  end_test
  exit 0
fi

if [ "$(grep -c "Termination:.*Backup OK" "${log_home}/parallel.out")" -ne 2 ]; then
  set_error "parallel NDMP backups did not both succeed"
fi

expect_grep "JobId ${jobids[0]}: Using Robot host:device.*${NDMJOB_ROBOT1_DIR}" \
  "${log_home}/parallel.out" "the first parallel job did not use robot 1"
expect_grep "JobId ${jobids[1]}: Using Robot host:device.*${NDMJOB_ROBOT2_DIR}" \
  "${log_home}/parallel.out" "the second parallel job did not use robot 2"

cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/overlap.out
sqlquery
SELECT CASE
         WHEN first.StartTime < second.EndTime
          AND second.StartTime < first.EndTime
         THEN 'overlap'
         ELSE 'serialized'
       END AS execution
FROM Job first, Job second
WHERE first.JobId = ${jobids[0]}
  AND second.JobId = ${jobids[1]};
END_OF_DATA

run_bconsole "${tmp}/bconcmds"
expect_grep "overlap" "${log_home}/overlap.out" \
  "NDMP jobs on the two robots did not overlap"

check_no_running_jobs

end_test
