#!/bin/sh
#
# @author Markus Raab <elektra@markus-raab.org>
# @brief Reformats the whole source code
# @date 18.02.2016
# @tags reformat

SCRIPTS_DIR=$(dirname "$0")
# shellcheck disable=SC1091 source=include-common
. "${SCRIPTS_DIR}/include-common"

MIN_VERSION=6
CLANG_FORMAT=$(command -v clang-format-$MIN_VERSION.0 || command -v clang-format)

if [ -n "$CLANG_FORMAT" ]; then
	LOCATION="$CLANG_FORMAT"
	VERSION=$("$CLANG_FORMAT" --version 2> /dev/null)
	MAJOR_VERSION=$(printf '%s' "$VERSION" | sed -E 's/.* ([0-9]+)\.[0-9].[0-9][ -].*/\1/')
	[ "$MAJOR_VERSION" -ge $MIN_VERSION ] 2> /dev/null || unset CLANG_FORMAT
fi

if [ -z "${CLANG_FORMAT}" ]; then
	printf >&2 'ClangFormat:   %s\n' "$LOCATION"
	printf >&2 'Version Info:  %s\n' "$VERSION"
	printf >&2 'Major Version: %s\n' "$MAJOR_VERSION"
	printf >&2 'Please install clang-format %s, or 7' "$MIN_VERSION"
	exit 1
fi

cd "$SOURCE" || {
	printf >&2 'Unable to change into source directory'
	exit 1
}

source_files=$(git ls-files '*.c' '*.h' '*.cpp' '*.hpp' '*.c.in' '*.h.in' | grep -v '^src/tools/gen.*')
printf "%s\n" "$source_files" | sed -nE 's/(.*)/'"'"'\1'"'"'/p' | xargs "$CLANG_FORMAT" -style=file -i
