#!/usr/bin/env bash

## Description: Run CSpell as the drupal.org cspell CI job does
## Usage: cspell [flags] [args]
## Example: "ddev cspell"
## ExecRaw: true

set -eu -o pipefail

CSPELL="$DDEV_COMPOSER_ROOT/$DDEV_DOCROOT/core/node_modules/.bin/cspell"
if ! "$CSPELL" --version >/dev/null 2>&1; then
  echo "cspell is not available. You may need to 'ddev exec \"cd $DDEV_DOCROOT/core && yarn install\"'"
  exit 1
fi

# CSpell does not follow the symlinks in the docroot, so it runs from the
# project root, with the configuration the CI job builds.
cd "$DDEV_COMPOSER_ROOT" || exit 1
TEMPLATES=https://git.drupalcode.org/project/gitlab_templates/-/raw/default-ref
REMOVE_CONFIG=0
if [ ! -f .cspell.json ]; then
  curl -sSL -o .cspell.json "$TEMPLATES/assets/.cspell.json"
  REMOVE_CONFIG=1
fi
curl -sSL -o prepare-cspell.php "$TEMPLATES/scripts/prepare-cspell.php"
CI_PROJECT_NAME="${DDEV_SITENAME//-/_}" _WEB_ROOT="$DDEV_DOCROOT" _CSPELL_DICTIONARY=.cspell-project-words.txt \
  php prepare-cspell.php >/dev/null
rm -f prepare-cspell.php

EXIT_CODE=0
"$CSPELL" -c .cspell.json --show-suggestions --show-context --no-progress "$@" . || EXIT_CODE=$?
if [ "$REMOVE_CONFIG" = 1 ]; then
  rm -f .cspell.json
fi
exit $EXIT_CODE
