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

# Change to the root directory of the project/module
CWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
pushd "$CWD/../.." >/dev/null

# 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\" before attempting to commit"
    exit 1
fi

# Work out what is staged for commit
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
        vendor/bin/php-cs-fixer -q -n --dry-run --rules="$(< build/php-cs-fixer.json)" fix "$file" </dev/null
        if [ $? == 8 ]; then
            vendor/bin/php-cs-fixer -q -n --rules="$(< build/php-cs-fixer.json)" fix "$file" </dev/null
            git add "$file"
        fi
        
        # 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 --standard=build/phpcs/php-format.xml --encoding=utf-8 -n --no-patch "$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 -n --standard=build/phpcs/php-format.xml --encoding=utf-8 "$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
