#!/bin/bash

# don't force line length -l=0
# don't change blank lines -fbl
# no spaces before semicolons -nsfs
# space before and after operators -bbao -baao
# no spaces around () [] {} -pt=2 -bt=2 -sbt=2
# stack closing tokens )} -sct
TIDY_ARGS="-l=0 -fbl -nsfs -baao -bbao -pt=2 -bt=2 -sbt=2 -sct"
check=

if test "$1"  = '--check'; then
    shift
    check=1
fi

if ! which perltidy > /dev/null 2>&1; then
    echo "No perltidy found, install it first!"
    exit 1
fi

cd "${0%/*}/.."

# just to make sure we are at the right location
test -e tools/tidy || exit 1

find -name '*.tdy' -delete

find . -name '*.p[lm]' -print0 | xargs -0 perltidy $TIDY_ARGS

find tools/absolutize -print0 | xargs -0 perltidy $TIDY_ARGS

while read file; do
    if ! diff -u ${file%.tdy} $file; then
        if test -n "$check"; then
            echo "RUN tools/tidy script before checkin"
            exit 1
        else
            mv -v $file ${file%.tdy}
        fi
    else
        rm $file
    fi
done < <(find . -name "*.tdy")

# vim: set sw=4 et:
