#!/usr/bin/env bash
#
# Git pre-commit hook to enforce coding standards
#
# @author      Steve Talbot
# @copyright   Copyright (c) Solviq Ltd 2016-7
# @license     MIT
# @package     solviq/skeleton-webapp

# Check that tools exist
if [[ ! -x vendor/bin/php-cs-fixer ]] || [[ ! -x vendor/bin/phpcbf ]] || [[ ! -x vendor/bin/phpcs ]]; then
    echo "Tools to enforce coding standards are not installed correctly:"
    echo "Please re-run \"composer install\" and \"npm install\" before attempting to commit"
    exit 1
fi

CWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
pushd "$CWD/../.." >/dev/null

violation=0
modified=`git diff --cached --name-only --diff-filter=ACM`

# Auto-format PHP and enforce coding standards
echo "Formatting PHP files and checking coding standards..."
while read -r file; do
    if [[ "${file##*.}" == "php" ]]; then
        echo "    $file"

        # PHP Coding Standard Fixer only sets useful exit codes on dry run;
		# it may read from stdin, so we explicitly supply a null stream
        vendor/bin/php-cs-fixer -q -n --dry-run --allow-risky=yes --rules="$(< ./build/php-cs-fixer/src-rules.json)" fix "$file" </dev/null
        if [ $? == 8 ]; then
        	vendor/bin/php-cs-fixer -q -n --allow-risky=yes --rules="$(< ./build/php-cs-fixer/src-rules.json)" fix "$file" </dev/null
        	git add "$file"
        fi

        # We could additionally use the dry run to check for syntax errors, however these will not be
        # displayed unless the -q option is removed

        # Squiz PHP Code Beautifier and Fixer outputs "Fixing file" if it changes anything;
		# it also reads from stdin, so we need to explicitly supply a null stream
        vendor/bin/phpcbf --encoding=utf-8 -n "$file" </dev/null |grep -q Fixing
        if [ $? == 0 ]; then
            git add "$file"
        fi

        # Squiz PHP Code Sniffer sets an exit code;
		# it also reads from stdin, so we need to explicitly supply a null stream
        vendor/bin/phpcs --encoding=utf-8 -n "$file" </dev/null
        if [ $? != 0 ]; then
            ((violation++))
        fi
    fi
done <<< "$modified"

# Allow commit?
popd >/dev/null
if (( violation > 0 )); then
    echo "Fix violation(s) before commit!"
    exit 1
fi
exit 0
