#!/usr/bin/env bash
#
# Runs PHP CodeSniffer against the staged files only, so that coding standard
# problems surface in under a second rather than in CI.
#
# Install with "ddev install-git-hooks".
# Bypass once with "git commit --no-verify", or always with SKIP_HOOKS=1.

set -uo pipefail

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

# Added, copied or modified only; deleted files cannot be sniffed. The
# extensions match phpcs.xml.dist.
mapfile -t FILES < <(git diff --cached --name-only --diff-filter=ACM -- \
  '*.engine' '*.inc' '*.info' '*.install' '*.module' '*.php' '*.profile' \
  '*.test' '*.theme' '*.yml')

[ ${#FILES[@]} -eq 0 ] && exit 0

if ! ddev describe >/dev/null 2>&1; then
  echo "pre-commit: DDEV is not running, skipping phpcs." >&2
  echo "            Start it with 'ddev start' to enable this check." >&2
  exit 0
fi

# Paths are relative to the repository root, which is /var/www/html inside the
# web container, so they need no rewriting.
ddev exec phpcs -s -- "${FILES[@]}"
