#!/usr/bin/env bash
#
# Copyright 2016-2021 Axel Huebl
#
# License: LGPLv3+

# search recursive inside a folder if a file contains end-of-line
#   (EOL) white spaces
#
# @result 0 if no files are found, else 1
#
# note: .md files can contain EOL white spaces for syntax reasons
#       (newline without starting a new paragraph)

ok=0
files=()

pattern="\.c$|\.cpp$|\.F90$|\.h$|\.H$|\.ini$|\.py$|"\
"\.rst$|\.sh$|\.tex$|\.txt$|\.xml$|\.yml$|"\
"CMakeLists\.txt|inputs"

for i in $(find . \
                -not -path "./.git/*"  \
                -not -path "./.spack-env/*" \
                -not -path "./.idea/*" \
                -type f | \
           grep -P "${pattern}")
do
  grep -q "[[:blank:]]\+$" $i
  if [ $? -eq 0 ]
  then
    files+=($i)
    echo "# $i contains EOL white spaces!"
    ok=1
  fi
done

if [ $ok -ne 0 ]
then
  echo "#"
  echo "# SUMMARY"
  echo "# -------"
  echo "# Run the following command(s) on the above files to remove your"
  echo "# end-of-line (EOL) white spaces:"
  echo ""
  echo "GNU_SED=\$(sed --help >/dev/null 2>&1 && { echo 1; } || { echo 0; })"
  echo "[[ \${GNU_SED} -eq 1 ]] && REPLACE=\"sed -i 's/[[:blank:]]\+$//'\" || REPLACE=\"sed -i '' -E 's/[[:blank:]]+$//'\""
  for i in ${files[@]}
  do
    echo "eval \${REPLACE} $i"
  done
fi

exit $ok
