#!/bin/bash
set -e
set -o pipefail
set -u

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

JobName=backup-bareos-fd

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

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

exit_with_error() {
  echo "$1"
  estat=1
  end_test
  exit 1
}

stop_bareos_daemons() {
  stop_bareos
}


# Fill ${BackupDirectory} with data.
setup_data

start_test

stop_bareos_daemons

cat <<END_OF_DATA >"${tmp}"/bconcmds
@$out ${NULL_DEV}
messages
@$out $tmp/log1.out
setdebug level=100 storage=File
label volume=TestVolume001 storage=File pool=Full
run job=$JobName yes
status director
status client
status storage=File
wait
messages
@#
@# now do a restore
@#
@$out $tmp/log2.out
wait
restore client=bareos-fd fileset=SelfTest where=$tmp/bareos-restores select all done
yes
wait
messages
quit
END_OF_DATA

start_dir
sleep 1

echo "Waiting for the director to start"
if ! echo "status dir" | "${BAREOS_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf > /dev/null 2>&1; then
  exit_with_error "Director did not start"
fi
echo "Director is running"

start_sd
start_fd

echo "Check if the filedaemon is connected to the director"
i=0
until echo "status dir" | \
  "${BAREOS_BCONSOLE_BINARY}" -c "$conf"/bconsole.conf | \
  grep --quiet --word-regexp "${TestName}-fd"; do
  echo "waiting for client to connect (#$i)... "
  ((i=i+1))
  sleep 1
  if [ $i -gt 60 ]; then
    exit_with_error "Filedaemon ${TestName} could not connect to director"
  fi
done

echo "Filedaemon is connected, running backup and restore"

run_bconsole "$tmp/bconcmds"

check_for_zombie_jobs storage=File

check_two_logs
check_restore_diff "${BackupDirectory}"
end_test
