#!/bin/sh

die () { echo "$*" 1>&2; exit 1; }

: ${UNCRUSTIFY_CMD:=uncrustify}
: ${UNCRUSTIFY_CFG:=uncrustify.cfg}

ERR=0

reformat () {
    while read file; do
        mv "$file" "$file".orig \
            || die "*** Failed to rename $file to $file.orig"

        # Convert ALL tabs to spaces, remove trailing whitespace, then format
        # It would be nice if uncrustify could do all this, but it doesn't
        # mess with comments (for example).

        if expand -t 4 "$file".orig > "$file" \
            && perl -i -pe 's/[ \f\r\t][ \f\r\t]*$//' "$file" \
            && "$UNCRUSTIFY_CMD" -c "$UNCRUSTIFY_CFG" --no-backup \
                    $UNCRUSTIFY_FLAGS "$file"; then
            rm -f "$file".orig
        else
            # Something went wrong
            mv -f "$file".orig "$file"
            echo "*** Format of $file FAILED!" 1>&2
            ERR=1
        fi
    done
}

# Use "*" here to avoid .*, such as .git
find * -type f | grep '\.[CcHh][Pp]*$' | reformat
exit $ERR
