#!/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

# Recreate the schema elements that existed in version 2250 so this test
# exercises the 2250 -> 2260 migration without depending on another test.
"${POSTGRES_BIN_PATH}/psql" -v ON_ERROR_STOP=1 "${db_name}" <<'SQL'
UPDATE public.Version SET VersionId = 2250;

ALTER TABLE public.Job ADD COLUMN HasBase SMALLINT DEFAULT 0;
ALTER TABLE public.JobHisto ADD COLUMN HasBase SMALLINT DEFAULT 0;

CREATE TABLE public.basefiles
(
    BaseId            SERIAL      NOT NULL,
    JobId             INTEGER     NOT NULL,
    FileId            BIGINT      NOT NULL,
    FileIndex         INTEGER,
    BaseJobId         INTEGER,
    PRIMARY KEY (BaseId)
);

CREATE INDEX basefiles_jobid_idx ON public.basefiles (JobId);

INSERT INTO public.basefiles (JobId, FileId, FileIndex, BaseJobId)
VALUES (1, 1, 1, 1);
SQL

set +e
update_output=$("${BAREOS_SCRIPTS_DIR}/update_bareos_tables" -f 2>&1)
update_rc=$?
set -e

if [ "${update_rc}" -eq 0 ]; then
  echo "update_bareos_tables unexpectedly succeeded"
  exit 1
fi

if ! grep -Fq \
  "Refusing to drop non-empty basefiles table during 2250 to 2260 migration" \
  <<<"${update_output}"; then
  echo "update_bareos_tables failed, but not for the expected reason"
  echo "${update_output}"
  exit 1
fi
