#!/bin/bash

# If CLANG_FORMAT_EXE exists in the environment,
# it is used instead of 'clang-format'.
CLANG_FORMAT_EXECUTABLE=${CLANG_FORMAT_EXE:-clang-format}

if ! [ -x "$(command -v ${CLANG_FORMAT_EXECUTABLE})" ]; then
  echo "***   ${CLANG_FORMAT_EXECUTABLE} could not be found."
  exit 1
fi

CLANG_FORMAT_VERSION="$(${CLANG_FORMAT_EXECUTABLE} --version)"
CLANG_FORMAT_MAJOR_VERSION=$(echo "${CLANG_FORMAT_VERSION}" | sed 's/^[^0-9]*\([0-9]*\).*$/\1/g')
CLANG_FORMAT_MINOR_VERSION=$(echo "${CLANG_FORMAT_VERSION}" | sed 's/^[^0-9]*[0-9]*\.\([0-9]*\).*$/\1/g')

if [ "${CLANG_FORMAT_MAJOR_VERSION}" -ne 8 ] || [ "${CLANG_FORMAT_MINOR_VERSION}" -ne 0 ]; then
  echo "***   This indent script requires clang-format version 8.0,"
  echo "***   but version ${CLANG_FORMAT_MAJOR_VERSION}.${CLANG_FORMAT_MINOR_VERSION} was found instead."
  exit 1
fi

find . -name '*.cpp' -o -name '*.hpp' | xargs ${CLANG_FORMAT_EXECUTABLE} -i

# Now also check for trailing whitspace. Mac OSX creates backup files
# that we need to delete manually.
find . -type f \( -name "*.md" -o -name "*.cc" -o -name "*.h" -o -name "*.txt" -o -name "*.cmake" \) |
  xargs -n 1 -P 10 -I {} bash -c "sed -i -e 's/\s\+$//g' {} && rm -f '{}-e'"

# Check that we do not introduce any file with the old copyright
./scripts/update-copyright
