#!/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

#
# back up and restore using the second two-drive robot
#

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

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

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

jobid=$(($(last_jobid_or_zero) + 1))

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

run_bconsole "${tmp}/bconcmds"

check_log "${log_home}/backup.out"
expect_grep "Termination:.*Backup OK" "${log_home}/backup.out" \
  "backup using robot 2 did not succeed"
expect_grep "${NDMJOB_ROBOT2_DIR}/drive0" "${log_home}/backup.out" \
  "drive 0 of robot 2 was not discovered"
expect_grep "${NDMJOB_ROBOT2_DIR}/drive1" "${log_home}/backup.out" \
  "drive 1 of robot 2 was not discovered"
expect_grep "Using Robot host:device.*${NDMJOB_ROBOT2_DIR}" \
  "${log_home}/backup.out" "robot 2 was not used for the backup"

rm -rf "${NDMP_FILESYSTEM}"

cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/restore.out
restore jobid=${jobid} client=${NDMPCLIENT} fileset=ndmp-fileset restorejob=NDMPRestoreDumpRobot2 all done yes
2
wait
messages
END_OF_DATA

run_bconsole "${tmp}/bconcmds"

check_log "${log_home}/restore.out"
expect_grep "Termination:.*Restore OK" "${log_home}/restore.out" \
  "restore using robot 2 did not succeed"
expect_grep "Using Robot host:device.*${NDMJOB_ROBOT2_DIR}" \
  "${log_home}/restore.out" "robot 2 was not used for the restore"

check_ndmp_data_full "${NDMP_FILESYSTEM}"
check_no_running_jobs

end_test
