#!/usr/bin/env bash

echo -e "husky default pre commit hook start"

BIN_PATH='{{BIN_PATH}}'
PHP_CS_FIXER="${BIN_PATH}/php-cs-fixer"
PHP_VERSION='{{PHP_VERSION}}'
PHP_PROJECT_PATH='{{PHP_PROJECT_PATH}}'

#cd ${PHP_PROJECT_PATH}
# Code conflict's check
for file in $(git --no-pager diff --cached --name-only)
do
    git show ":$file" | grep "<<< HEAD" > /dev/null
    if [ $? -eq 0 ]; then
        echo -e "\033[31m\033[43;31m${file}\033[0;31m Your code has conflict!\033[0m"
        exit 1
    fi
done

#cd -
# php-cs-fixer's check
HAS_PHP_CS_FIXER=false

if [ -x "$PHP_CS_FIXER" ]; then
    HAS_PHP_CS_FIXER=true
fi

if $HAS_PHP_CS_FIXER; then

    if [[ ${PHP_VERSION} == '{{''PHP_VERSION}}''}}' ]];then
        PHP_VERSION=$(php -v | awk -F ' ' '{print $2}' | head -n 1 | awk -F '.' '{print $1$2}')
    fi

    CONFIG_FILE="${BIN_PATH}/.php${PHP_VERSION}_cs"

    if [ -e "${PHP_PROJECT_PATH}/.php_cs" ];then
        CONFIG='--config=.php_cs'
    elif [ -e ${CONFIG_FILE} ];then
        CONFIG="--config=${CONFIG_FILE}"
    else
        CONFIG='--rules=@PSR2'
    fi

    git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | while read line; do
        output=$(${PHP_CS_FIXER} fix ${CONFIG} --verbose ${line} --using-cache=no 2>&1)
        echo "${output}"
        if ! echo "$output" | grep -E '^[\.F]$'; then
            echo -e "\033[31mAttention：\033[43;31m${line}\033[0;31m,which not success !\033[0m"
            exit 1
        fi
        git add "$line"
    done
    code=$?
    if [ ${code} -ne 0 ];then
        echo -e "\033[31mhusky default pre commit hook interrupt\033[0m"
        exit ${code}
    fi
else
    echo ""
    echo "Please install php-cs-fixer, e.g.:"
    echo ""
    echo "  composer require --dev friendsofphp/php-cs-fixer:^2.14.0"
    echo ""
fi

echo -e "husky default pre commit hook finish"
