#!/usr/bin/env bash

## Command provided by https://github.com/ddev/ddev-drupal-contrib (modified — drops #ddev-generated)
## Description: Run eslint inside the web container
## Usage: eslint [flags] [args]
## Example: "ddev eslint"
## ExecRaw: true

set -eu -o pipefail

if "$DDEV_DOCROOT/core/node_modules/.bin/eslint" --version >/dev/null ; then
  # Configure prettier
  test -e .prettierrc.json || ln -s $DDEV_DOCROOT/core/.prettierrc.json .
  test -e .prettierignore || echo '*.yml' > .prettierignore
  # Change directory to the project root folder
  cd "$DDEV_DOCROOT/$DRUPAL_PROJECTS_PATH/${DDEV_SITENAME//-/_}" || exit
  # Use local eslint config if present, mirroring drupalci behavior. The
  # local config is expected to extend ../../../core/.eslintrc.passing.json
  # itself if it wants core's rules.
  if compgen -G ".eslintrc*" >/dev/null || compgen -G "eslint.config.*" >/dev/null ; then
    ESLINT_CONFIG=()
  else
    ESLINT_CONFIG=(--config="../../../core/.eslintrc.passing.json")
  fi
  # If caller passed specific .js/.yml files (e.g. from pre-commit), lint those
  # only; otherwise default to scanning the entire module.
  TARGETS=(.)
  for arg in "$@"; do
    case "$arg" in *.js|*.yml|*.yaml) TARGETS=() ; break ;; esac
  done
  "$DDEV_COMPOSER_ROOT/$DDEV_DOCROOT/core/node_modules/.bin/eslint" "${ESLINT_CONFIG[@]}" --no-error-on-unmatched-pattern --ignore-pattern="*.es6.js" --resolve-plugins-relative-to=$DDEV_COMPOSER_ROOT/$DDEV_DOCROOT/core --ext=.js,.yml "${TARGETS[@]}" "$@"
else
  echo "eslint is not available. You may need to 'ddev exec \"cd $DDEV_DOCROOT/core && yarn install\"'"
  exit 1
fi
