#!/bin/bash
# COMMANDS
PHP="docker-compose exec -T php php"

# Variables
PROJECT_DIR=`$PHP -r "echo dirname(dirname(dirname(realpath('$0'))));"`
DIFF_FILES=`git diff --cached --name-only --diff-filter=ACMR HEAD web`

# ERROR FLAGS
ERROR_DUMP=0
ERROR_PARSE=0
ERROR_PHP_CS=0

# COLORS
GREEN='\e[0;32m'
BROWN='\e[0;33m'
RED='\e[0;31m'
CYAN='\e[96m'
NC='\e[0m'

FILES=''
echo -e "${GREEN}Checking PHP ${BROWN}dpm ${GREEN}and ${BROWN}lint${GREEN}...${NC}"
for FILE in $DIFF_FILES; do
    DIFF=`git diff --cached --diff-filter ACMR $FILE|grep -e '+.*dpm'`
    if [ ! -z "$DIFF" ]; then
        FILES="${FILES}\n\t$FILE"
        ERROR_DUMP=1
    fi
    $PHP -l -d display_errors=0 $PROJECT_DIR/$FILE
    if [ $? != 0 ]; then
        ERROR_PARSE=1
    fi
done
if [ $ERROR_PARSE != 0 ]; then
    echo -e "${RED}Fix parsing errors before commit.${NC}"
fi
if [ $ERROR_DUMP != 0 ]; then
    echo -e "${RED}Remove dpm statement in following files before commit.${NC}$FILES"
fi

FILES=''
echo -e "${GREEN}Checking ${GREEN}PHP code standards...${NC}"
for FILE in $DIFF_FILES; do
    FILES="$FILES $PROJECT_DIR/$FILE"
done
if [ ! -z "$FILES" ]; then
    $PHP ./vendor/bin/phpcs --report=diff -n --standard=vendor/drupal/coder/coder_sniffer/Drupal $FILES
    if [ $? != 0 ]; then
        ERROR_PHP_CS=1
    fi
    $PHP ./vendor/bin/phpcs --standard=vendor/drupal/coder/coder_sniffer/DrupalPractice $FILES
    if [ $? != 0 ]; then
        ERROR_PHP_CS=1
    fi
fi
if [ $ERROR_PHP_CS != 0 ]; then
    echo -e "${RED}Fix the phpcs error(s) before commit.${NC}"
fi

# Display message and exit status
! (( $ERROR_DUMP || $ERROR_PARSE || $ERROR_PHP_CS ))
ERRORS=$?
[ $ERRORS == 0 ] && echo -e "${CYAN}You can commit your job!${NC}"
[ $ERRORS != 0 ] && echo -e "${RED}Fix the errors before commit!${NC}"

exit $ERRORS
