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

#
# make sure we can copy ndmp jobs, and also restore them afterwards
#

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

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

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

start_test

# first run the copy jobs
cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${log_home}/copy.out
run job=ndmp-copy-${NDMPCLIENT} yes
wait
messages
@$out ${log_home}/copies.out
list jobs
END_OF_DATA

run_bconsole "${tmp}/bconcmds"
check_log "${log_home}/copy.out"

# the copies of the full and the last incremental backup
copy_jobids=$(awk -F'|' '$7 ~ /^ *C *$/ {print $2+0}' "${log_home}/copies.out" | sort -n)
full_copy_jobid=$(head -n 1 <<<"${copy_jobids}")
last_incr_copy_jobid=$(tail -n 1 <<<"${copy_jobids}")
if [ "$(wc -l <<<"${copy_jobids}")" -ne 11 ]; then
  set_error "expected 11 copied jobs, got: ${copy_jobids}"
  exit 1
fi

# then restore a full copy
rm -rf "${NDMP_FILESYSTEM}"

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

run_bconsole "${tmp}/bconcmds"
check_log "${log_home}/restore-full.out"
expect_grep "Termination:.*Restore OK" "${log_home}/restore-full.out" \
  "restore of the full copy did not succeed"
check_ndmp_data_full "${NDMP_FILESYSTEM}"

# afterwards restore an incremental copy
rm -rf "${NDMP_FILESYSTEM}"

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

run_bconsole "${tmp}/bconcmds"
check_log "${log_home}/restore-incr.out"
expect_grep "Termination:.*Restore OK" "${log_home}/restore-incr.out" \
  "restore of the incremental copy did not succeed"
tail -n 1 "${NDMP_FILESYSTEM}/incremental" | grep -q "^incremental-10$" \
  || set_error "wrong content of the restored incremental file"

check_for_zombie_jobs storage=ndmpfile client=bareos-fd

end_test
