#!/bin/bash

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

#
# make sure we can restore a specific incremental backup
# by passing file= on restore cmd line
#

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

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

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

start_test

# remove files
cleanup_remote

# beware of https://github.com/bareos/internal/issues/447
echo "################ restore incremental by file #####################"
cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/restore-file.out
restore jobid=10 client=ndmp-fd fileset=${NDMP_CLIENT}-fileset restorejob=NDMPRestoreDump file="${NDMP_TEST_PATH}/subdir/subtestfile1" file="${NDMP_TEST_PATH}/subdir/subtestfile2" yes
wait
message
END_OF_DATA

run_bconsole "${tmp}/bconcmds"

# Beware of File count mismatch, there's always only one file restored.
if ! check_log "${log_home}/restore-file.out"; then
  if [ ${bstat} -eq 0 ] && [ ${rstat} -eq 1 ]; then
    echo "Restore warning: known issue with NDMP restore."
    rstat=0
  else
    echo "Restore failed and backup was not successful. This is an unexpected issue."
    exit 1
  fi
fi

ndmp_ssh "cat \"${NDMP_TEST_PATH}/subdir/subtestfile1\"" | diff - sbin/bareos_dir-ndmp-native
ndmp_ssh "cat \"${NDMP_TEST_PATH}/subdir/subtestfile2\"" | diff - sbin/bareos_sd-ndmp-native

#check_for_zombie_jobs storage=ndmpfile client=ndmp-fd

end_test
