#!/usr/bin/env bash

## Description: Run CSpell the way the GitLab cspell job runs it
## Usage: cspell [flags] [args]
## Example: "ddev cspell" or "ddev cspell --show-suggestions"
## ExecRaw: true

# Provided by this project, not by ddev-drupal-contrib, which has no cspell
# command. It reproduces the cspell job from the Drupal Association templates:
# https://project.pages.drupalcode.org/gitlab_templates/jobs/cspell/
#
# Two details matter for matching CI:
#  - CSpell cannot follow symlinks, so it runs from the project root rather
#    than from web/modules/custom/apisync.
#  - prepare-cspell.php only wires in the project dictionary when
#    _CSPELL_DICTIONARY is exported, so a bare cspell run misses it.

set -eu -o pipefail

REF=default-ref
BASE="https://git.drupalcode.org/project/gitlab_templates/-/raw/${REF}"

cd "${DDEV_COMPOSER_ROOT}" || exit 1

if [ ! -x "${DDEV_DOCROOT}/core/node_modules/.bin/cspell" ]; then
  echo "cspell is not available. Run:"
  echo "  ddev exec \"cd ${DDEV_DOCROOT}/core && yarn install\""
  exit 1
fi

# The templates modify .cspell.json in place, so always start from a fresh
# copy of the default rather than from the previous run's output.
curl -sfL -o .cspell.json "${BASE}/assets/.cspell.json"
curl -sfL -o prepare-cspell.php "${BASE}/scripts/prepare-cspell.php"

export _CSPELL_DICTIONARY="${_CSPELL_DICTIONARY:-.cspell-project-words.txt}"
php prepare-cspell.php >/dev/null
rm -f prepare-cspell.php

"${DDEV_DOCROOT}/core/node_modules/.bin/cspell" \
  -c .cspell.json --show-suggestions --show-context --no-progress \
  --exclude '.planning/**' "$@" .
