#!/bin/bash

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

JobName=backup-s3-fd

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

#shellcheck source=../scripts/functions
. "${rscripts}"/functions
"${rscripts}"/cleanup
"${rscripts}"/setup

"${rscripts}"/start_minio.sh "$MINIO_PORT" "$TestName"

# shortcut for s3cmd
S3="${S3CMD} --no-check-certificate --config ${S3CFG}"

$S3 mb S3://backup


# Fill ${BackupDirectory} with data.
setup_data

start_test

cat <<END_OF_DATA >$tmp/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
setdebug level=100 storage=File
label volume=TestVolume001 storage=File pool=Full
run job=$JobName yes
status director
status client
status storage=File
wait
messages
@#
@# now do a restore
@#
@$out $tmp/log2.out
wait
restore client=bareos-fd fileset=SelfTest where=$tmp/bareos-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bareos "$@"
check_for_zombie_jobs storage=File

check_two_logs
check_restore_diff "${BackupDirectory}"

# In case we want to tackle the close_wait issue
#bareos_sd_pid=$(pidof bareos_sd-${TestName})
#if [ $(lsof -p ${bareos_sd_pid} | grep -c "CLOSE_WAIT") -ne 0 ]
#then
#   echo "Error: Connection CLOSE_WAIT found"
#   estat=1
#fi

"${rscripts}"/stop_minio.sh "$TestName"

end_test
