#!/usr/bin/env 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

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

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

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

# Check that the storage correctly swaps a loaded tape from one device
#  to the next, when necessary.

start_test

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
messages
@$out ${tmp}/mount.out
mount drive=1 slot=1
setdevice storage=File device=File2 autoselect=no
setdevice storage=File device=File3 autoselect=no
setdevice storage=File device=File4 autoselect=no
@$out ${tmp}/job.out
run job=backup-bareos-fd yes
wait
messages
setdevice storage=File device=File2 autoselect=yes
setdevice storage=File device=File3 autoselect=yes
setdevice storage=File device=File4 autoselect=yes
END_OF_DATA

run_bconsole "$@"

expect_grep "3001 Mounted Volume: .*" "${tmp}/mount.out" "volume was not mounted"
expect_grep "Backup OK" "${tmp}/job.out" "Backup was not successful"

expect_grep 'Using Device "File1" (storage/drv_0) to write.' \
  "${tmp}/job.out" \
  "job used the wrong device"

expect_grep 'Issuing autochanger "unload slot 1, drive 1" command.' \
  "${tmp}/job.out" \
  "slot 1 was not unloaded from drive 1"

expect_grep 'Issuing autochanger "load slot 1, drive 0" command.' \
  "${tmp}/job.out" \
  "slot 1 was not loaded into drive 0"

expect_grep 'Autochanger "load slot 1, drive 0", status is OK.' \
  "${tmp}/job.out" \
  "slot 1 was not successfully loaded into drive 0"

end_test
