#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

set +e

git diff-index --cached --name-only HEAD | while read -r file; do
	case "$file" in
		*.vue | *.js | *.json | *yml | *.md) fmt='Prettier' ;;
		*.php) fmt='PHP CS Fixer' ;;
		*) continue ;;
	esac

	printf "Checking format of $file... "

	case "$fmt" in
		Prettier)
			cmd='npm run fix'
			out=$(git show :$file | node_modules/.bin/prettier --check --stdin-filepath "$file" 2>&1)
		;;

		'PHP CS Fixer')
			cmd='composer fix'
			out=$(git show :$file | php-cs-fixer fix - --dry-run --diff 2>&1)
		;;
	esac

	if [ $? == 0 ]; then
		printf 'correct.\n'
		continue
	fi

	printf "incorrect.\n\n\
$fmt: Incorrectly formatted file: $file.
Run \"$cmd\" to fix it, then stage the result.\n\n"

	exit 1
done

format=$?
[ $format != 0 ] && exit $format
printf 'All files correctly formatted.\n\n'

set -e
phpunit
printf '\n'
