#!/bin/bash

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

#
# check that bareos actually selects the archive
#   to restore instead of just picking the newest one.
#

set -e
set -o pipefail
set -u

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

JobName=backup-bareos-fd

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

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

start_test

file="$(pwd)/tmp/data/weird-files/socket.pl"
if [[ -f "$tmp/bareos-restores/$file" ]]; then
  rm "$tmp/bareos-restores/$file"
fi
echo "i overwrite the file" >"$file"
cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
setdebug level=100 storage=File
@$out ${runner_tmp}/log1.out
status director
status client
status storage=File
wait
messages
@$out ${runner_tmp}/jobs.out
list jobs
@$out ${runner_tmp}/create-newer-backup.out
update jobid=1 jobtype=A
run job=$JobName
yes
wait
messages
quit
END_OF_DATA

run_bconsole
# find the new job id
backupid=$(grep 'Job queued. JobId=' "${runner_tmp}/create-newer-backup.out" | sed -n -e 's/^.*JobId=//p')
cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
setdebug level=100 storage=File
@$out ${runner_tmp}/log1.out
status director
status client
status storage=File
wait
@$out ${runner_tmp}/restore-archive.out
restore archive
5
mark $file
done
yes
wait
messages
delete jobid=$backupid
quit
END_OF_DATA
run_bconsole

check_for_zombie_jobs storage=File

check_preconditions

# since we changed the file they cannot be the same!
if cmp -s "${runner_tmp}/bareos-restores/$file" "$file"; then
  exit 2
fi

# since the other tests do not care for the original contents
# we just leave the changed file instead of changing it back.

end_test
