#!/bin/bash

#   BAREOS® - Backup Archiving REcovery Open Sourced
#
#   Copyright (C) 2024-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.
#

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

JobName=ai-backup-bareos-fd

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

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

# Check whether duplicate consolidate job are cancelled.

cat <<END_OF_DATA >$tmp/bconcmds
@$out $tmp/extra.out
messages
@$out $tmp/consolidate-duplicates_incr.out
@exec "sh -c 'touch ${tmp}/data/weird-files/file-19'"
run job=$JobName level=Incremental yes
wait
@exec "sh -c 'touch ${tmp}/data/weird-files/file-20'"
run job=$JobName level=Incremental yes
wait
@exec "sh -c 'touch ${tmp}/data/weird-files/file-21'"
run job=$JobName level=Incremental yes
wait
@$out $tmp/consolidate-duplicates_incr-messages.out
messages
END_OF_DATA
run_bconsole
when="$(date "+%F %H:%M:%S" --date="@$(($(date +%s) + 5))")"
echo "running consolidate when=${when}"
cat <<END_OF_DATA >$tmp/bconcmds
@$out $tmp/consolidate-duplicates_consolidate.out
run job=Consolidate when="${when}" yes
run job=Consolidate when="${when}" yes
wait
@$out $tmp/consolidate-duplicates_consolidate-messages.out
messages
END_OF_DATA
run_bconsole

expect_grep "JobId [[:digit:]]* already running. Duplicate consolidation job of Client \".*\" and FileSet \".*\" not allowed." \
  "$tmp"/consolidate-duplicates_consolidate-messages.out \
  "duplicate consolidate virtualfull did not log duplicate job error."

expect_grep "Termination:[[:space:]]*Backup Canceled" \
  "$tmp"/consolidate-duplicates_consolidate-messages.out \
  "duplicate consolidate virtualfull was not cancelled."

expect_grep "Termination:[[:space:]]*Backup OK" \
  "$tmp"/consolidate-duplicates_consolidate-messages.out \
  "both consolidate virtualfull did not succeed."

end_test
