#!/bin/sh
#
# @author René Schwaiger <sanssecours@me.com>
# @brief Reformats CMake source code
# @date 07.05.2018
# @tags reformat

SCRIPTS_DIR=$(dirname "$0")
. "${SCRIPTS_DIR}/include-common"

CMAKE_FORMAT=$(which cmake-format)

cd "$SOURCE"

if [ -z "${CMAKE_FORMAT}" ]; then
	printf 2>&1 'Please install `cmake-format`\n'
	exit 1
fi

output=$("${CMAKE_FORMAT}" 2>&1 CMakeLists.txt)

if [ $? != 0 ]; then
	printf 2>&1 'It seems your local installation of `cmake-format` is broken:\n\n%s' "$output"
	exit 1
fi

if [ -z "$(which sponge)" ]; then
	printf 2>&1 'Please install `sponge`\n'
	exit 1
fi

for file in $(find . \( -name 'CMakeLists.txt' -or -name '*.cmake' \) -and \
	\( \
	-path './benchmarks/*' \
	-or -path './cmake/*' \
	-or -path './doc/*' \
	-or -path './examples/*' \
	-or -path './scripts/*' \
	-or -path './src/*' \
	-or -path './tests/*' \
	-or -path './CMakeLists.txt' \
	\)
); do
	$CMAKE_FORMAT "$file" | unexpand | sponge "$file"
done
