#!/bin/bash
# Pre-commit Git hook.
# Runs PHP CS Fixer on PHP files.
#
# If you absolutely must commit without testing,
# use: git commit --no-verify

# This will check only staged files to be commited.
filenames=($(git diff --staged --name-only HEAD))

# This will set text to red in terminal.
text_red=`tput setaf 1`
# This will set the text to green in terminal.
text_green=`tput setaf 2`
# This will reset the terminal text to normal.
text_reset=`tput sgr0`

numberFilesChanged="${#filenames[@]}"

if [[ $numberFilesChanged > 0 ]];
then
    echo "$numberFilesChanged files were changed, running php-cs-fixer"
    # PHP CS Fixer.
    for i in "${filenames[@]}"
    do
        if [[ $i == *.php ]];
        then
            php php-cs-fixer.phar fix $i

      	    if [ $? -ne 0 ];
            then
              # File had some issues. Now it is fine. Add this file to git again.
              git add $i
            fi
        fi
    done
fi

echo "${text_green}PHP CS Fixer finished execution successfully.${text_reset}"
