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

#
# verify that "update volume volstatus=" refuses status changes that
# would lose data unless "force" is given
#

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}/backup.out
run job=${regularjob_name} level=Full yes
wait
messages
quit
END_OF_DATA

run_bconsole

volume=$(sed -n -r -e 's/^ *Volume name\(s\): *([^| ]+).*/\1/p' \
  "${log_home}/backup.out" | tail -n 1)
if [ -z "${volume}" ]; then
  set_error "Could not find the volume written by the backup."
  end_test
fi

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${log_home}/refused.out
update volume=${volume} volstatus=Used
update volume=${volume} volstatus=Used
update volume=${volume} volstatus=Recycle
update volume=${volume} volstatus=Cleaning
llist volume=${volume}
@$out ${log_home}/forced.out
update volume=${volume} volstatus=Recycle force
update volume=${volume} volstatus=Used
@$out ${log_home}/empty.out
label volume=VolStatusEmpty storage=File pool=Full
update volume=VolStatusEmpty volstatus=Cleaning
quit
END_OF_DATA

run_bconsole

expect_grep "Volume status is already: Used" \
  "${log_home}/refused.out" \
  "Setting the current status again was not reported as unchanged."

expect_grep "Only Purged volumes can be set to Recycle" \
  "${log_home}/refused.out" \
  "Recycle of a volume with jobs was not refused."

expect_grep "still contains jobs" \
  "${log_home}/refused.out" \
  "Cleaning of a volume with jobs was not refused."

expect_grep "volstatus: Used" \
  "${log_home}/refused.out" \
  "Refused changes modified the volume status."

expect_not_grep "New Volume status is: \(Recycle\|Cleaning\)" \
  "${log_home}/refused.out" \
  "A refused status change was written."

expect_grep "New Volume status is: Recycle" \
  "${log_home}/forced.out" \
  "force did not override the Recycle check."

expect_grep "New Volume status is: Cleaning" \
  "${log_home}/empty.out" \
  "An empty volume could not be set to Cleaning."

end_test
