#!/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
# using restore + mark

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

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

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

start_test

# remove files
cleanup_remote

echo "################ restore first incremental by mark #####################"
cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/restore-mark.out
restore jobid=2 client=ndmp-fd fileset=${NDMP_CLIENT}-fileset where="/" restorejob=NDMPRestoreDump
mark ${NDMP_TEST_PATH}/incremental
done
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-mark.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

# we deterministically use one jobid and look that we found the corresponding incremental
# here the restore should be the first incremental
if ! ndmp_ssh "tail -c 200 \"${NDMP_TEST_PATH}/incremental\" | xargs | grep -F -- \"${NDMP_HOST_ADDRESS}-1\""; then
  echo "Restored file ${NDMP_TEST_PATH}/incremental is not the expected first Incremental"
  rstat=1
fi

#check_for_zombie_jobs storage=ndmpfile client=ndmp-fd

end_test
