#!/bin/sh

# Title
echo "\n\033[42;30m   Guns.com   \033[43;32m\033[43;30m   Images API   \033[33;100m\033[42;100m   Pre-push hook   \033[49;90m"
echo "\033[0m"

# Logger
log () {
    now=$(date +%T)
    case $1 in
        debug)
            echo " $now \033[42;100m[DEBUG]\033[0m - $2 ";
            ;;
        info)
            echo " $now \033[44;30m[INFO]\033[0m - $2 ";
            ;;
        warning)
            echo " $now \033[43;30m[WARNING]\033[0m - $2 ";
            ;;
        error)
            echo " $now \033[41;97m[ERROR]\033[0m - $2 ";
            ;;
    esac
}

log "debug" "Start Git pre-push steps"

# Check for not commited files
log "debug" "Check for changes in index files..."
FIRST_GREP=$(git status --porcelain | egrep "^\s*?[A-Z]" | wc -l)
if [ ${FIRST_GREP} -ne 0 ] ; then
    log "warning" "There are changes not staged for commit"
fi

# PHPUnit
log "debug" "Starting PHPUnit tests\n"
if ! docker-compose run php php ./vendor/bin/simple-phpunit --stop-on-failure ; then
    log "error" "PHPUnit tests not passed"
    exit 1
fi
echo "\n"
log "info" "PHPUnit tests are passed"

# PHPCSFixer
log "debug" "Starting PHPCSFixer\n"
docker-compose run php php ./vendor/bin/php-cs-fixer fix --using-cache=no
echo "\n"
SECOND_GREP=$(git status --porcelain | egrep "^\s*?[A-Z]" | wc -l)
if [ ${FIRST_GREP} -ne ${SECOND_GREP} ] ; then
    log "error" "There is some files were changed by PHPCSFixer. You should commit changes before push"
    git status
    exit 1
fi

log "info" "All steps are passed, now pushing..."

exit 0
