#!/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
. "${BAREOS_SCRIPTS_DIR}"/functions
"${BAREOS_SCRIPTS_DIR}"/cleanup
"${BAREOS_SCRIPTS_DIR}"/setup

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

assert_fd_not_listening()
{
  local port
  port="${BAREOS_FD_PORT}"

  if "${PYTHON_EXECUTABLE}" - "${port}" <<'PY'
import socket
import sys

port = int(sys.argv[1])
targets = [("127.0.0.1", socket.AF_INET), ("::1", socket.AF_INET6)]

for host, family in targets:
    try:
        sock = socket.socket(family, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        rc = sock.connect_ex((host, port))
        sock.close()
        if rc == 0:
            print(f"FD listener accepts connections on {host}:{port}")
            sys.exit(1)
    except OSError:
        pass

sys.exit(0)
PY
  then
    return 0
  fi

  exit_with_error \
    "Filedaemon is listening on port ${port} but client-initiated-only mode requires no listener"
}

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 "${BAREOS_CONFIG_DIR}"/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 "${BAREOS_CONFIG_DIR}"/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"
assert_fd_not_listening

run_bconsole "${tmp}/bconcmds"

check_for_zombie_jobs storage=File

check_two_logs
check_restore_diff "${BackupDirectory}"
end_test
