#!/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

files=$(git ls-files '*.cmake' '*/CMakeLists.txt' 'CMakeLists.txt')
printf "%s\n" "$files" | sed -nE 's/(.*)/'"'"'\1'"'"'/p' | xargs "$CMAKE_FORMAT" -i
for file in $files; do
	unexpand "$file" | sponge "$file"
done
