#!/bin/bash
set -e
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
}

# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data "$@"

start_test

stop_bareos_daemons

cat <<END_OF_DATA >"${tmp}"/bconcmds
@$out /dev/null
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

"${rscripts}"/bareos-ctl-dir start
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"

"${rscripts}"/bareos-ctl-sd start
"${rscripts}"/bareos-ctl-fd start

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

"${rscripts}"/bareos-ctl-dir stop
"${rscripts}"/bareos-ctl-sd stop
"${rscripts}"/bareos-ctl-fd stop

check_two_logs
check_restore_diff "${BackupDirectory}"
end_test
