#!/bin/bash

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

#
# files the data server fails to recover are reported per file
# (NDMP_LOG_FILE), are not counted as restored and fail the restore
#

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

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

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

readonly_dir="${tmp}/readonly"
rm -rf "${readonly_dir}"
mkdir -p "${readonly_dir}"
chmod 0555 "${readonly_dir}"
if [ -w "${readonly_dir}" ]; then
  echo "cannot create a read-only directory (running as root?), skipping"
  chmod 0755 "${readonly_dir}"
  end_test
  exit 0
fi

cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/restore.out
restore jobid=1 client=${NDMPCLIENT} fileset=ndmp-fileset restorejob=NDMPRestoreDump where=^${readonly_dir}/restore all done yes
1
wait
messages
END_OF_DATA

run_bconsole "${tmp}/bconcmds"
chmod 0755 "${readonly_dir}"

expect_grep "Termination:.*Restore Error" \
  "${log_home}/restore.out" "restore did not fail"
expect_grep "failed to recover 7 of 7 files" "${log_home}/restore.out" \
  "failed files were not reported"
expect_grep "Files Restored: *0$" "${log_home}/restore.out" \
  "failed files were counted as restored"

check_no_running_jobs

end_test
