#!/usr/bin/env bash

# This hook verifies that the changes are formatted using clang-format.
# It has to be installed in:
#  - .git/hooks/pre-commit in linphone-sdk

# Add here all folders where we want this hook to apply
folders_to_check="bctoolbox|belcard|belle-sip|belr|liblinphone|mediastreamer2|ortp"

files="$(git diff --name-only --cached --diff-filter=ACMR | grep -E "^$folders_to_check" | grep -E '\.(c|cc|cpp|h|hh)$')"

# Do nothing if none is affected
if [[ -z "$files" ]]; then
  exit 0
fi

if ! [ -x "$(command -v clang-format)" ]; then
	echo "Pre commit hook: Please install clang-format (coding style checker) - could not find clang-format in PATH."
	exit 1
fi

files_to_format=""

while read -r line; do
  if ! clang-format --style=file -Werror -n $line > /dev/null 2>&1; then
    files_to_format+="$line "
  fi
done <<< "$files"

if [[ ! -z "$files_to_format" ]]; then
	echo "*****************"
	echo ""
	echo "Pre commit hook: Staged file(s) contains non correctly formatted code. Please correct it using one of the following:"
	echo "1) Configure your IDE to format automatically on save (entire file)"
	echo "2) Use clang-format to correctly format source code using:"
	echo "   clang-format --style=file -i $files_to_format"
	echo ""
	echo "*** Aborting commit.***"
	exit 1
fi
