#!/usr/bin/env bash
SE=0

# Helpful methods
success() {
  read message;
  echo -e -n "\033[32m  ✔ "
  echo ${message};
  echo -e -n "\033[39m"
}

title() {
  read message;
  echo -e -n "\033[33m ====> "
  echo ${message};
  echo -e -n "\033[39m"
}

error() {
  read message;
  echo -e -n "\033[31m  ✗ "
  echo ${message};
  echo -e -n "\033[39m"
}

exists() {
    type "$1" > /dev/null 2>&1
}
# PHP linting
echo -n "Checking PHP files" | title

# Initial Counts
filesFailed=0
filesPassed=0
filesChecked=0


# Loop through install, module and php files
for entry in `git diff --name-only --cached | grep -E '\.php$'`
do
  # May want to add support for specifying PHP path
  # Tosses out regular output, we only care about errors.
  currLint=`php -l ${entry} 2>&1 1>/dev/null`
  # Check for Linting issues.
  if [[ ${#currLint} == 0 ]]; then
    ((filesPassed++))
    if exists php-cs-fixer ; then
      # Run CS Fixer
      php-cs-fixer fix ${entry} 2>&1 1>/dev/null
      # Remove empty change.
      git checkout -- ${entry}
    fi
  else
    echo -e "Failed: ${entry}" | error
    echo -e "${currLint}\n" | error
    ((filesFailed++))
  fi
  ((filesChecked++))
done

  echo -e "${filesPassed} Passed" | success

  # Output a nice Pass / Fail
  if [[ ${filesFailed} > 0 ]]; then
    echo -e "${filesFailed} Failed" | error
    echo -n "===> There were syntax errors with your php, aborting" | error
    exit 1
  else
    echo -n "No syntax errors" | success
  fi

echo -e "\n";

# PHPUnit

echo -n "Running unit tests" | title

./vendor/bin/phpunit --colors 2>&1 1> /tmp/phpunit &

# Spinner
pid=$!
spin='-\|/'
i=0
while kill -0 $pid 2>/dev/null
do
  i=$(( (i+1) %4 ))
  printf "\r\033[33m ${spin:$i:1} \033[39m"
  sleep .1
done
printf "\r";

RESULT=$( cat /tmp/phpunit );


if [[ ${RESULT} =~ FAILURES ]]
then
printf "\033[31m";
echo "$RESULT";
printf "\033[39m";
echo -e "\n";
echo -n "Tests failed!" | error
exit 1
fi

echo "Unit tests passed" | success;

printf "\n";

echo "😎 "
