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

#
# NDMP_NATIVE: ndmjob emulates the NDMP DATA, TAPE and ROBOT agents
#

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

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

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

make_ndmp_data_full
save_ndmp_reference

start_ndmjob
setup_ndmjob_robot "${NDMJOB_ROBOT1_DIR}"
setup_ndmjob_robot "${NDMJOB_ROBOT2_DIR}"

bin/bareos start
bin/bareos status

cat <<END_OF_DATA >"${tmp}/bconcmds"
@$out ${tmp}/robot1-status.out
status storage=ndmjob
@$out ${tmp}/robot2-status.out
status storage=ndmjob-robot2
@$out ${tmp}/setup.out
update slots storage=ndmjob
update slots storage=ndmjob-robot2
label barcodes storage=ndmjob drive=0 slot=1-2 pool=ndmp-tape yes
label barcodes storage=ndmjob drive=1 slot=3-5 pool=ndmp-tape yes
label barcodes storage=ndmjob-robot2 drive=0 slot=6-7 pool=ndmp-tape-robot2 yes
label barcodes storage=ndmjob-robot2 drive=1 slot=8-10 pool=ndmp-tape-robot2 yes
wait
messages
list volumes
END_OF_DATA

run_bconsole "${tmp}/bconcmds"

for drive in \
  "${NDMJOB_ROBOT1_DIR}/drive0" "${NDMJOB_ROBOT1_DIR}/drive1"; do
  if ! grep -Fq "${drive}" "${tmp}/robot1-status.out"; then
    echo "drive ${drive} is missing from robot 1" >&2
    exit 1
  fi
done

for drive in \
  "${NDMJOB_ROBOT2_DIR}/drive0" "${NDMJOB_ROBOT2_DIR}/drive1"; do
  if ! grep -Fq "${drive}" "${tmp}/robot2-status.out"; then
    echo "drive ${drive} is missing from robot 2" >&2
    exit 1
  fi
done

if ! grep -q "PTAG00XX" "${tmp}/setup.out" \
  || ! grep -q "PTAG09XX" "${tmp}/setup.out"; then
  echo "labeling the volumes of both ndmjob robots failed" >&2
  exit 1
fi
