#!/bin/bash
#
# Git pre-commit hook to reject code violating coding standards
#
# @author      Steve Talbot
# @copyright   Copyright (c) 2014-17 Solviq Ltd
# @license     MIT
# @package     solviq/attachment-php


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"
    	vendor/bin/phpcbf --standard=dev/phpcs/php-format.xml --encoding=utf-8 "$file" |grep Fixing
    	if [ $? == 0 ]; then
    		git add "$file"
    	fi
		vendor/bin/phpcs -n --standard=dev/phpcs/php-format.xml --encoding=utf-8 "$file"
		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
