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

# This script is symlinked from a vendor directory
BASEDIR=`git rev-parse --show-toplevel`
pushd "$BASEDIR" >/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-CS-Fixer only sets useful exit codes on dry run;
		# it may read from stdin, so we explicitly supply a null stream
		# and we use the -q option to suppress display of syntax errors
		if [[ -x vendor/bin/php-cs-fixer ]]; then
            vendor/bin/php-cs-fixer -q -n --dry-run fix "$file" </dev/null
            if [ $? == 8 ]; then
                vendor/bin/php-cs-fixer -q -n fix "$file" </dev/null
                git add "$file"
            fi
        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
		if [[ -x vendor/bin/phpcbf ]]; then
            vendor/bin/phpcbf -n "$file" </dev/null |grep -q Fixing
            if [ $? == 0 ]; then
                git add "$file"
            fi
        fi

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

    if [[ "$file" == "composer.json" ]]; then
        echo "    $file"

        # Do not allow commit with a "path" repository
        if grep -q -e "\"type\"\s*:\s*\"path\"" "$file"; then
            printf "\nCannot commit composer.json with a \"path\" repository type\n\n"
            ((violation++))
        fi
    fi
done <<< "$modified"

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