#!/usr/bin/env bash
#
# Runs the same checks the GitLab pipeline runs, before anything leaves the
# machine. Fast-fails on the first gate that reports a problem.
#
# Install with "ddev install-git-hooks".
# Bypass once with "git push --no-verify", or always with SKIP_HOOKS=1.
# Skip one gate with SKIP_COMPOSER_LINT, SKIP_PHPCS, SKIP_PHPSTAN or
# SKIP_PHPUNIT set to 1.
#
# cspell, eslint and stylelint are deliberately left to CI: they need Drupal
# core's node modules, which would make every push slow. Run them on demand
# with "ddev eslint" and "ddev stylelint".
#
# The phpunit gate runs the unit and kernel levels only. The functional tests
# install a Drupal site per test class, which is minutes rather than seconds,
# and CI runs the whole suite anyway. Run them before a merge request with
# "ddev phpunit tests/src/Functional".

set -uo pipefail

# git writes "<local ref> <local sha> <remote ref> <remote sha>" lines on
# stdin. Drain them, or git can block writing to a pipe nothing reads.
cat >/dev/null

[ "${SKIP_HOOKS:-0}" = "1" ] && exit 0

if ! ddev describe >/dev/null 2>&1; then
  echo "pre-push: DDEV is not running, so the checks cannot run." >&2
  echo "          Run 'ddev start', or push with --no-verify." >&2
  exit 1
fi

gate() {
  local skip_var=$1 label=$2
  shift 2
  if [ "${!skip_var:-0}" = "1" ]; then
    printf '  skip   %s (%s=1)\n' "$label" "$skip_var"
    return 0
  fi
  printf '  run    %s\n' "$label"
  if ! "$@"; then
    printf '\npre-push: %s failed. Fix it, or push with --no-verify.\n' "$label" >&2
    return 1
  fi
}

# The composer-lint job validates the module's own composer.json from the
# symlinked module directory, not from the project root. Running it at the root
# picks up the assembled site's vendor/ and fails on blocked Composer plugins
# rather than on anything wrong with the module.
composer_lint() {
  ddev exec 'cd "${DDEV_DOCROOT}/${DRUPAL_PROJECTS_PATH}/${DDEV_SITENAME//-/_}" && composer validate' &&
    ddev exec 'vendor/bin/parallel-lint -e php,module,inc,install,test,profile,theme,engine \
      --exclude web --exclude vendor --exclude node_modules --no-progress .'
}

# One path argument at a time: the ddev phpunit command shifts $1 as the test
# path and passes the rest to phpunit as flags.
phpunit_fast() {
  ddev phpunit tests/src/Unit && ddev phpunit tests/src/Kernel
}

echo "pre-push: running the CI checks."
gate SKIP_COMPOSER_LINT 'composer lint' composer_lint &&
  gate SKIP_PHPCS   'phpcs'   ddev phpcs &&
  gate SKIP_PHPSTAN 'phpstan' ddev phpstan &&
  gate SKIP_PHPUNIT 'phpunit (unit + kernel)' phpunit_fast
