#!/bin/bash

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 or later of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see
# https://www.gnu.org/licenses/licenses/gpl-3.0.en.html.
#
# Copyleft (C) 2025  Johann Brault-Baron <johann.brault_baron@yahoo.com>
#

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ -z "$*" ] ; then cat << EOF
usage  $(basename "$0") <file> ..
  Removes trailing whitespace characters from every line of every <file>.
  Returns 1 if some modification occurred.
EOF
exit
fi

if [ -z "$*" ] ; then
   exit 0
fi

readarray -t NON_SYM <<< "$(find -P "$@")"
if [ -z "${NON_SYM[*]}" ] ; then
   exit 0
fi

readarray -t FILES <<< "$(grep -I -l "[ "$'\t'"]$" "${NON_SYM[@]}")"
if [ -n "${FILES[*]}" ] ; then
   sed -i 's/[ '$'\t''][ '$'\t'']*$//' "${FILES[@]}"
   exit 1
fi
