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

#
# Restore files and filter them with FileRegex
#

set -e
set -o pipefail
set -u

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

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

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

# Use own restore directory to ensure it is always
# clean before restore
RestoreDirectory="${runner_tmp}/fileregex-restores"

start_test

fileregex=".*/[Aa]-file.*"

matched_files=()
while IFS= read -r -d $'\0'; do
  matched_files+=("$REPLY")
done < <(find "$BackupDirectory/" -type f -regex "$fileregex" -print0)

echo "Matched files:" >"${runner_tmp}/matched.out"
for file in "${matched_files[@]}"; do
  echo "$file" >>"${runner_tmp}/matched.out"
done

if [ "${#matched_files[@]}" -eq 0 ]; then
  echo "FileRegex did not match any files in test data"
  exit 1
fi

# Restore all files but filter by fileregex
cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${runner_tmp}/jobs.out
list jobs
@$out ${runner_tmp}/restore.out
restore client=bareos-fd fileset=SelfTest \
    where="$RestoreDirectory" \
    fileregex="$fileregex" \
    yes
wait
messages
quit
END_OF_DATA

run_bconsole
check_for_zombie_jobs storage=File

check_preconditions

# We expect to restore exactly those files
# matched by the regex
check_restore_files_diff "${matched_files[@]}"

end_test
