#!/bin/bash

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

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

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

start_test

command_count=0

echo "executing ${BAREOS_RANDOM_COMMANDS_BINARY}"
${BAREOS_RANDOM_COMMANDS_BINARY} --zero --count 100 2>"${log_home}/seed.out" | while read -d $'\0' -r command; do
  echo "executing command ${command_count}" 1>&2
  cat <<END_OF_DATA
@$out $log_home/last-command.out
@echo ${command_count}
@$out $log_home/command-${command_count}.out
${command}
.
.
.
.
END_OF_DATA
  if ! bin/bareos status >${NULL_DEV}; then
    echo "loop detected that bareos died" 1>&2
    break
  fi

  command_count=$((command_count + 1))
done | bin/bconsole

if ! bin/bareos status >"${NULL_DEV}"; then
  # we managed to create a crash, lets try to find out
  # where it went wrong

  # last_command is the _offset_ of the last tried command
  last_command=$(tail -n2 "${log_home}/last-command.out" | head -n1)

  cat <<EOF | tee "${log_home}/crash.out"
    CRASH!
    $(cat "${log_home}/seed.out")
    crashed at: ${last_command}
EOF
  exit 1
fi

cat <<END_OF_DATA >"$tmp/bconcmds"
@$out $log_home/messages.out
messages
quit
END_OF_DATA
run_bconsole || echo "result = $?"

expect_not_grep "ERROR" \
  "${log_home}/messages.out" \
  "found (prevented) crash for seed $(cat "${log_home}/seed.out")"

end_test
