#!/bin/sh

STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E "\.(js|ts|tsx|jsx)$")
ESLINT="$(git rev-parse --show-toplevel)/node_modules/.bin/eslint"
CONFIG_FILE="$(git rev-parse --show-toplevel)/wmc-eslint/eslint.config.js"

if [[ "$STAGED_FILES" = "" ]]; then
  exit 0
fi

PASS=true

echo "Validating JavaScript and TypeScript:"

# Check for eslint
which eslint &> /dev/null
if [[ ! -x "$ESLINT" ]]; then
  echo "Please install ESlint (npm i --save --save-exact --dev eslint)"
  exit 1
fi

for FILE in $STAGED_FILES
do
  output="$($ESLINT "$FILE")"

  if [[ "$?" == 0 ]]; then
    echo "$(tput setaf 2)ESLint Passed: $FILE$(tput sgr0)"
  else
    echo "$output" | sed -E "s/([0-9]+:[0-9]+)\s+error/$(tput setaf 1)\1 error$(tput sgr0)/g"
    echo "$(tput setaf 1)ESLint Failed: $FILE$(tput sgr0)"
    PASS=false
  fi
done

echo "JavaScript and TypeScript validation completed!"

if ! $PASS; then
  echo "$(tput setaf 1)COMMIT FAILED:$(tput sgr0) Your commit contains files that should pass ESLint but do not. Please fix the ESLint errors and try again."
  exit 1
else
  echo "$(tput setaf 2)COMMIT SUCCEEDED$(tput sgr0)"
fi

exit $?
