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

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

myname=$(basename "$0")

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

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

start_test

mkdir -p "${tmp}/data"
echo "$0" >"${tmp}/data/${myname}"

# this looks weird but im not sure how to output the files in a better way
(
  echo -n "sample_one "
  cat "${DB_FILE}"
  echo -e "\r"
  echo -n "Bareos "
  cat "${DB_FILE2}"
  echo -e "\r"
) >"${tmp}/backed-up-data.out"

# we want to make sure that the original files dont need to exist anymore
# for the restore
rm "${DB_FILE}"
rm "${DB_FILE2}"

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
messages
@$out "${tmp}/${myname}.log"
setdebug level=300 client trace=1
restore client=bareos-fd fileset=DBFileStream where=/ pluginoptions=mssqlvdi:serveraddress=${HOSTNAME}:instance=default:database=DBFileStreamTest:norecovery=yes:replace=yes:recoverafterrestore=yes select all done yes
wait
setdebug level=10 client trace=0
messages
quit
END_OF_DATA

run_bconsole

#check_for_zombie_jobs storage=File

print_delete_trace

check_log "${tmp}/${myname}.log"
# check that the updated content is there
"${SQLCMD}" -Q "SELECT * FROM DBFileStreamTest.tests.samples" >"$tmp/sql-stream-samples-check.out"
expect_grep "Bareos" "$tmp/sql-stream-samples-check.out" "Bareos not found in samples"

"${SQLCMD}" -Q "SELECT fstream_id, fstream_name, fstream_binary.PathName() FROM DBFileStreamTest.tests.files" >"$tmp/sql-stream-files-check.out"
expect_grep "Bareos" "$tmp/sql-stream-files-check.out" "Bareos not found in files"

# there is probably a better way to check this ...
"${SQLCMD}" -E -Q "set NOCOUNT on; select fstream_name, CONVERT(VARCHAR(50), fstream_binary, 0) as fstream_content from DBFileStreamTest.tests.files" -h -1 -W >"${tmp}/restored-data.out"

diff "${tmp}/restored-data.out" "${tmp}/backed-up-data.out"
end_test
