#!/bin/bash

#   BAREOS® - Backup Archiving REcovery Open Sourced
#
#   Copyright (C) 2025-2025 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 multiple jobs and verify that you can prune a single volume
#

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 ${NULL_DEV}
messages
@$out ${log_home}/backup.out
label volume=TestVolume001 storage=File pool=Full
label volume=TestVolume002 storage=File pool=Full
label volume=TestVolume003 storage=File pool=Full
label volume=TestVolume004 storage=File pool=Full
label volume=TestVolumeIncremental storage=File pool=Incremental
status director
status client
status storage=File
wait
run job=${regularjob_name} Level=Full yes
run job=${regularjob_name} Level=Full yes
messages

@$out ${log_home}/restore.out
@#
@# now do a restore
@#
wait
restore client=bareos-fd fileset=SelfTest where=$tmp/bareos-restores select all done
yes
wait
messages

@# wait for retention period
@sleep 2

@$out ${log_home}/prune.out
@#
@# now prune using the commandline
@#
update volume=TestVolume001 volstatus=Used
prune volume=TestVolume001 yes
wait
quit
END_OF_DATA

run_bconsole

check_for_zombie_jobs storage=File
check_two_logs "${log_home}/backup.out" "${log_home}/restore.out"

## Prune volumes
expect_grep "Purging the following 2 JobIds: 1,2" \
  "${log_home}/prune.out" \
  "Pruned jobs from volume pruning not found" \
  "Purging the"

expect_grep "Volume \"TestVolume001\" contains no jobs after pruning." \
  "${log_home}/prune.out" \
  "Volume still contains jobs, or wrong volume pruned." \
  "Volume.*contains no jobs after pruning."

end_test
