#!/bin/bash

STANDARD="PSR12"
BIN="./vendor/bin"

echo
echo "PHP_CodeSniffer pre-commit hook – commit with the --no-verify option to skip the hook"
echo

# Check whether PHP_CodeSniffer can be found
if [ ! -f "$BIN/phpcs" ]
then
    echo "PHP_CodeSniffer not found – is it installed? 'composer require --dev squizlabs/php_codesniffer'"
    echo
    exit 1
fi

# Retrieve staged files
FILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD)

# Run the sniffer
echo "Running PHP_CodeSniffer using the $STANDARD standard"
echo
PHPCS=("$BIN/phpcs" "--standard=$STANDARD" "--filter=gitstaged" "--encoding=utf-8" "-p" ".")
"${PHPCS[@]}"

# Syntax OK
if [ $? == 0 ]
then
    echo "No violations detected"
    echo
    exit 0
fi

# Fix automatically?
read -p "Automatically fix violations when possible? [Y/n]: " < /dev/tty
if [[ ! ("$REPLY" == 'y' || "$REPLY" == 'Y' || "$REPLY" == '') ]]
then
    echo
    exit 1
fi

# Run the beautifier
PHPCBF=("$BIN/phpcbf" "--standard=$STANDARD" "--filter=gitstaged" ".")
"${PHPCBF[@]}"

# Stage the files
echo "Re-staging updated files"
echo
git add ${FILES}

# Run the sniffer again
"${PHPCS[@]}"

# Some violations remain
if [ $? != 0 ]
then
    echo "PHP_CodeSniffer was not able to fix all of the violations, please fix the remaining ones manually or commit with the --no-verify option"
    echo
    exit 1
fi