#!/bin/sh
#
# check that all code complies w/ the clang-format specification
#
# if all is well, returns w/o errors and does not print anything.
# otherwise, return an error and print offending changes

set -e # abort on error

if [ $# -ne 1 ]; then
    echo "\033[31mERROR\033[0m"\
         "wrong number of arguments"
    echo "\tusage: check_format <DIR>\n"
    exit 1
fi

_binary=${CLANG_FORMAT_BINARY:-clang-format}

$_binary --version

cd $1
find . \( -iname '*.cpp' -or -iname '*.hpp' -or -iname '*.ipp' -or -iname '*.cu' -or -iname '*.cuh' \) \
       -and -not -path "./*build*/*" \
       -and -not -path "./thirdparty/*" \
  | xargs $_binary -i -style=file


if ! [ -z $CI ] || ! [ -z $GITHUB_ACTIONS ]; then
  mkdir changed
  for f in $(git diff --name-only); do
    cp --parents $f changed
  done
fi

echo "\033[32mINFO\033[0m"\
     "clang-format done"

set +e
git diff --exit-code --stat
result=$?

if [ "$result" -eq "128" ] || [ "$result" -eq "129" ]; then
    echo "\033[33mWARNING\033[0m"\
         "Could not create summary of affected files"
    echo "\tFormat was successfully applied"
    echo "\tAre you in a submodule?"
    echo "\tYou could try running check_format with sudo.\n"
fi

exit $result
