#!/usr/bin/env bash

: ${REPOSITORY_ROOT:="$(dirname $0)"/../..}
: ${SCRIPTS_ROOT:="${REPOSITORY_ROOT:?}"/scripts}
: ${BASH_TOOLBOX:="${SCRIPTS_ROOT:?}/bash-toolbox"}
# NOTE: `die` logs an error then exits.
source "${BASH_TOOLBOX:?}"/die.sh
# NOTE: `edo` supports dry mode via `DRY_MODE`. When not in dry mode,
#   logs the command as a `TRACE` and executes it.
source "${BASH_TOOLBOX:?}"/edo.sh

OPENAPI_DOCS_DIR="${REPOSITORY_ROOT:?}"/docs/openapi
OPENAPI_SPEC_FILE="${OPENAPI_DOCS_DIR:?}"/openapi.yaml
REDOCLY_CONFIG_FILE="${OPENAPI_DOCS_DIR:?}"/redocly.cfg.yaml

if ! command -v redocly &>/dev/null; then
    die "$(format_hyperlink "Install $(format_code redocly)" "https://redocly.com/docs/cli/installation") first ($(format_code 'npm i -g @redocly/cli@1') / $(format_code 'volta install @redocly/cli@1'))."
fi
if ! [[ "$(redocly --version)" == 1.* ]]; then
    die "Only Redocly CLI v1 is supported (for now). Install it with $(format_code 'npm i -g @redocly/cli@1') / $(format_code 'volta install @redocly/cli@1')."
fi

# NOTE: `2> >(awk 'NR>12' >&2)` hides
#   >
#   > ╔═══════════════════════════════════════════════════════╗
#   > ║                                                       ║
#   > ║  A new version of Redocly CLI (2.14.5) is available.  ║
#   > ║  Update now: `npm i -g @redocly/cli@latest`.          ║
#   > ║  Changelog: https://redocly.com/docs/cli/changelog/   ║
#   > ║                                                       ║
#   > ╚═══════════════════════════════════════════════════════╝
#   >
#   > Using Redoc community edition.
#   > Login with redocly login or use an enterprise license key to preview with the premium docs.
#   >
edo redocly preview-docs "${OPENAPI_SPEC_FILE:?}" --port=8081 --config="${REDOCLY_CONFIG_FILE:?}" "$@" \
    2\> \>\(awk \"NR\>12\" \>\&2\)
