#!/bin/bash

# Single space, newline at the end of file, and remove trailing whitespace from source files.
. `dirname -- ${BASH_SOURCE[0]}`/common_functions.sh
setup_trap
cd_top
use_pygrep
check_fast_mode_flag

# Clear lines that only contain whitespace, compress multiple empty lines
# into a single line, discard trailing empty lines.
# Add a newline to the end of the file if there is not one.
whitespace()
{
    ! head $1 | grep -q 'automatically generated by SWIG' || return
    if [[ "$1" == *.py ]]; then
        # Special handling for Python, which allows multiple empty lines.
        cat $1 | sed -e 's/[[:space:]]*$//' > $t
        test "$(tail -c 1 "$1" | wc -l)" -eq 0 && echo >> $t
    else
        # All other file types.
        (cat $1 && echo) | sed -e 's/[[:space:]]*$//' | \
            cat -s | \
            sed -e '${' -e '/^$/d' -e '}' > $t
    fi
    cmp $t $1 > /dev/null 2>&1 || (echo "$1" && cp $t $1)
}

# Parallel execution: if it's the main onvocation of the script, collect the file names
# to process and run them in subprocesses.
is_main_run && {
    find bench examples ext src test tools/checksum_bitflip \
        -name '*.[ch]' -o \
        -name '*.cpp' -o \
        -name '*.dox' -o \
        -name '*.in' -o \
        -name '*.py' -o \
        -name '*.sh' -o \
        -name '*.yaml' -o \
        -name '*.yml' -o \
        -name 's_*' -o \
        -name 'CONFIG.*' -o \
        -name 'Makefile.am' | \
        $FGREP -v \
            -e 'Makefile.in' \
            -e 'checksum/power8' \
            -e '3rdparty' \
            -e 'docs/tools' \
            -e 'log/log_auto' \
    | do_in_parallel
    exit $?
}

# A list of files provided: process them one by one.

for f in "$@"; do
    whitespace $f
done

exit 0
