#! /bin/bash
# vim: set filetype=sh:

# notrail: Removes all trailing spaces from text files

# Copyright (C) 2004-2013 by Brian Lindholm.  This file is part of the
# littleutils utility set.
#
# The notrail utility 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; either version 3, or (at your option) any later version.
#
# The notrail utility 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
# the littleutils.  If not, see <https://www.gnu.org/licenses/>.

# get a valid temporary directory and set up traps
TMPWILD=`tempname -w notrail_$$` || exit 99
trap 'rm -f ${TMPWILD} ; exit 1' 1 2 3 13 15
trap 'rm -f ${TMPWILD} ; exit 0' 0

# get command-line options
VERBOSITY=1
while getopts hqv opts
do
  case $opts in
    h) echo 'notrail 1.2.3'
       echo 'usage: notrail [-h(elp)] [-q(uiet)] [-v(erbose)] filename ...'
       exit 0 ;;
    q) VERBOSITY=$((${VERBOSITY}-1)) ;;
    v) VERBOSITY=$((${VERBOSITY}+1)) ;;
    *) echo 'notrail 1.2.3'
       echo 'usage: notrail [-h(elp)] [-q(uiet)] [-v(erbose)] filename ...'
       exit 1 ;;
  esac
done
shift `expr ${OPTIND} - 1`

# run through the files
while [ $# -gt 0 ]; do

  # make sure we can read and modify file
  if [ ! -f "$1" -o ! -r "$1" -o ! -w "$1" ]; then
    echo "notrail warning: $1 is not a writeable non-directory file"
    shift; continue
  fi

  # run through sed
  TMPFILE=`tempname notrail_$$` || exit 99
  sed -e 's/ *$//' "$1" > ${TMPFILE}

  # replace if changes occurred
  cmp -s "$1" ${TMPFILE}
  if [ $? -eq 1 ]; then
    cp ${TMPFILE} "$1"
    if [ "$VERBOSITY" -gt 0 ]; then
      echo "$1: trailing space removed"
    fi
  elif [ "$VERBOSITY" -gt 1 ]; then
    echo "$1: unchanged"
  fi

  # clean up afterwards
  rm -f ${TMPFILE}
  shift

done
rm -f ${TMPWILD}
