#!/usr/bin/env bash

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

set -eu -o pipefail

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

# Build .cspell.json from the gitlab_templates default, as the CI job does.
curl -sSLO https://git.drupalcode.org/project/gitlab_templates/-/raw/default-ref/scripts/prepare-cspell.php
curl -sSL -o .cspell.json https://git.drupalcode.org/project/gitlab_templates/-/raw/default-ref/assets/.cspell.json
export CI_PROJECT_NAME="${DDEV_SITENAME//-/_}"
export _WEB_ROOT="$DDEV_DOCROOT"
export _CSPELL_DICTIONARY=.cspell-project-words.txt
export _CSPELL_IGNORE_STANDARD_FILES=1
php prepare-cspell.php
rm -f prepare-cspell.php

EXIT_CODE=0
"$CSPELL" -c .cspell.json --show-suggestions --show-context --no-progress "$@" . || EXIT_CODE=$?
rm -f .cspell.json
exit $EXIT_CODE
