#!/bin/sh
# $Id: addtrailingnl 53031 2009-04-10 18:26:20Z cxh $
# Add a trailing newline
# Usage: addtrailingnl [-n] file [file2 . . .]
# If -n is present, then don't modify the file, only print

tmpfile=/tmp/addtrailingnl.$$ 

nlfile=/tmp/addtrailingnl_nlfile.$$
echo "foo" | awk '{printf("\n")}' > $nlfile

filesupdated=/tmp/addtrailingnl_filesupdated.$$

printonly=no
if [ "$1" = "-n" ]; then
    shift
    printonly=yes
fi

files=$@
for file in $files
do
    #echo "$0: $file"
    results=`tail -1 $file | od -bv | tail -2 |head -1 | egrep '012 *$'`
    if [ "x$results" = "x" ]; then
	if [ "$printonly" = "no" ]; then
	    echo "$file: does not have a trailing newline, adding one now."
	    #cvs annotate $file | tail -1
	else    
	    echo "$file: does not have a trailing newline, would add one."
        fi
        cat  $file $nlfile > $tmpfile
	if [ "$printonly" = "no" ]; then
            cp $tmpfile $file
	    echo "Not running svn commit, just copying"
	    #svn commit -m "Added trailing newline" $file
	    echo $file >> $filesupdated
	else    
	    echo "$file: would commit"
	    diff $file $tmpfile
        fi
    fi
done

if [ "$printonly" = "no" ]; then
    echo "Thes files should be checked in:"
    cat $filesupdated
fi

rm -f $tmpfile $nlfile $filesupdated
