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

# Make sure that the storage daemon does _not_ try to use a same volume to
# write & read the virtualfull.

start_test

# We run one full and two virtual fulls. This way the second virtual full
# needs to read the volume from the first virtual full.  This tests that
# the second virtual full does _not_ try to write into that volume as well,
# as that would cause a deadlock.

# The full will write into the Incremental Poll
# The first vf will read from Incremental, and write into Full-0
# The second vf will read from Full-0, and write to Full-0

run_bconsole - <<END_OF_DATA
@$out ${NULL_DEV}
messages
@$out ${tmp}/job-full.out
run job=backup-bareos-fd level=Full yes
wait
messages
@$out ${tmp}/job-vf-1.out
run job=backup-bareos-fd level=VirtualFull yes
wait
messages
@$out ${tmp}/job-vf-2.out
run job=backup-bareos-fd level=VirtualFull yes
END_OF_DATA

# This job may hang if it tries to read & write to the same volume
LAST_JOB=$(last_jobid_or_zero)

# If the last virtual full job is not done after 30 seconds, then it
# probably ran into a dead lock.  The job is relatively small, so it
# should take way less time than that.
run_bconsole - <<END_OF_DATA
@$out ${tmp}/msgs.out
wait timeout=30 jobid=${LAST_JOB}
messages
END_OF_DATA

check_log "${tmp}/msgs.out"
expect_grep "Termination:.*OK" \
  "${tmp}/msgs.out" \
  "No job was successful"

end_test
