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

BASE_DIR="$(git rev-parse --show-toplevel)"
cd $BASE_DIR
if [ ! -f "scripts/apply-clang-format" ]; then
  echo "***   The indenting script must be executed from within the Kokkos clone!"
  exit 1
fi

TRACKED_FILES="$(git ls-files)"

find ${TRACKED_FILES} \
  -type f -name '*.cpp' -o -name '*.hpp' -o -name '*.cc' -o -name '*.h' |
  xargs -n 1 -P 10 ${CLANG_FORMAT_EXECUTABLE} -i

# Now also check for trailing whitspace. Mac OSX creates backup files
# that we need to delete manually.
TRACKED_FILES="$(git ls-tree HEAD --name-only)"
find ${TRACKED_FILES} \
  -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/check-copyright
