#!/bin/bash
#   BAREOS® - Backup Archiving REcovery Open Sourced
#
#   Copyright (C) 2026-2026 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

JobName=bconsole-status-catalog
#shellcheck source=../../scripts/functions
. "${BAREOS_SCRIPTS_DIR}"/functions

start_test

assert_contains()
{
  local file=$1
  local pattern=$2
  if ! grep -Eq "$pattern" "$file"; then
    set_error "Pattern '$pattern' not found in $file"
    estat=1
  fi
}

cat <<END_OF_DATA >"$tmp"/bconcmds
@$out $tmp/status-catalog-default.txt
status catalog
@$out ${NULL_DEV}
.api 2
@$out $tmp/status-catalog.json
status catalog
@$out ${NULL_DEV}
.api 0
END_OF_DATA

run_bconsole

assert_contains "$tmp/status-catalog-default.txt" "^Catalog Status:"
assert_contains "$tmp/status-catalog-default.txt" "^[[:space:]]+Status: (ok|warning|error|unavailable)$"
assert_contains "$tmp/status-catalog-default.txt" "^[[:space:]]+Checked at: "
assert_contains "$tmp/status-catalog-default.txt" "^[[:space:]]+Catalog: "
assert_contains "$tmp/status-catalog-default.txt" "^[[:space:]]+Engine: postgresql$"
assert_contains "$tmp/status-catalog-default.txt" "Largest tables:"
assert_contains "$tmp/status-catalog-default.txt" "Rows \(est\.\)"

assert_contains "$tmp/status-catalog.json" "\"catalog_status\""
assert_contains "$tmp/status-catalog.json" "\"status\"[[:space:]]*:[[:space:]]*\"(ok|warning|error|unavailable)\""
assert_contains "$tmp/status-catalog.json" "\"checked_at\""
assert_contains "$tmp/status-catalog.json" "\"catalog\""
assert_contains "$tmp/status-catalog.json" "\"engine\"[[:space:]]*:[[:space:]]*\"postgresql\""
assert_contains "$tmp/status-catalog.json" "\"tables\""
assert_contains "$tmp/status-catalog.json" "\"rows\""

end_test
