#!/usr/bin/env bash

# From https://gitlab.com/gitlab-org/gitlab-runner/-/blob/main/scripts/lint-docs

set -o pipefail
GIT_ROOT=$(cd "${BASH_SOURCE%/*}" && git rev-parse --show-toplevel)
cd ${GIT_ROOT}
VALE_MIN_ALERT_LEVEL=${VALE_MIN_ALERT_LEVEL:-}
VALE_OUTPUT=${VALE_OUTPUT:-}
ERROR_RESULTS=0
if command -v vale >/dev/null 2>&1; then
    args=()
    if [ -n "${VALE_MIN_ALERT_LEVEL}" ]; then
        args+=("--minAlertLevel" "${VALE_MIN_ALERT_LEVEL}")
    fi
    if [ "${VALE_OUTPUT}" == "line" ]; then
        args+=("--output" "line" "--sort" "--normalize")
    fi
    if [ "${VALE_OUTPUT}" == "json" ]; then
        args+=("--output" "./Documentation/.vale/vale-json.tmpl")
    else
        echo "Lint prose"
    fi

    # TODO: "Documentation"
    vale "${args[@]}" web/content || ((ERROR_RESULTS++))
else
    echo "vale is missing, please install it from https://errata-ai.gitbook.io/vale/#installation"
fi
if [ "${VALE_OUTPUT}" == "json" ]; then
    exit 0
fi

if [ "${ERROR_RESULTS}" -ne 0 ]; then
    echo "✖ ${ERROR_RESULTS} Vale spell check failed. Review the log carefully to see full listing."
    exit 1
else
    echo "✔ Vale spell check passed"
    exit 0
fi
