#!/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> ..
  Makes sure that every <file> ends with exactly one end of line.
  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 NON_BIN <<< "$(grep -l -I "" "${NON_SYM[@]}")"
if [ -z "${NON_BIN[*]}" ] ; then
   exit 0
fi

readarray -t BROKEN <<< "$(tail -v -c2 "${NON_BIN[@]}" |
   tr -d $'\n' |
   sed "s/==> /\n/g" |
   grep -v '<==.$' |
   sed 's/ *<==\(\|..\)$//'
)"

if [ -n "${BROKEN[*]}" ] ; then
   sed -z "s/\n*$/\n/" -i "${BROKEN[@]}"
   echo "fixed end of file of: ${BROKEN[*]}" >&2
   exit 1
fi
