#!/usr/bin/env sh
#
# SPDX-License-Identifier: GPL-2.0-only

# DESCR: Run clang-format on white-listed directories

LINTDIR="$(
  cd -- "$(dirname "$0")" > /dev/null 2>&1 || return
  pwd -P
)"

# shellcheck source=helper_functions.sh
. "${LINTDIR}/helper_functions.sh"

# Until we require this by default, we need a list of opted-in directories
# If the script isn't looking at a git repository, just exit
if [ ! -f .clang-format-scope ] || [ "${IN_GIT_TREE}" -eq 0 ]; then
	exit 0
fi

files_to_check=$(${GIT} log HEAD~..HEAD --format= --name-only $(cat .clang-format-scope) | grep "\.[ch]$")

# nothing to do
if [ -z "$files_to_check" ]; then
	exit 0
fi

if [ $(clang-format $files_to_check | wc -l) -gt 0 ]; then
	if [ "$(${GIT} diff --no-prefix HEAD~..HEAD -- $files_to_check | clang-format-diff)" != "" ]; then
		echo "Coding style mismatch. The following patch fixes it:"
		${GIT} diff --no-prefix HEAD~..HEAD -- $files_to_check | clang-format-diff
		exit 0
	fi
fi