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

: ${FORMAT:=stylish}
[ -n "$GITHUB_ACTIONS" ] && FORMAT='github-actions'

# NOTE: `2> >(sed '1,/╚/ d')` 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/   ║
#   > ║                                                       ║
#   > ╚═══════════════════════════════════════════════════════╝
edo redocly lint "${OPENAPI_SPEC_FILE:?}" --format "${FORMAT:?}" --config="${REDOCLY_CONFIG_FILE:?}" "$@" \
    2\> \>\(sed '1,/╚/ d'\)

# TODO: Check that all routes from children files are included in `openapi.json`.
