#!/bin/bash
#
# This file is part of rasdaman community.
#
# Rasdaman community 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 of the License, or
# (at your option) any later version.
#
# Rasdaman community 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 rasdaman community.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Peter Baumann /
# rasdaman GmbH.
#
# For more information please see <http://www.rasdaman.org>
# or contact Peter Baumann via <baumann@rasdaman.com>.
#
########################################################################

#
# This script reformats the C++/Java code in the rasdaman repository with astyle.
# Execute either
#  * with no arguments from the top-level source directory, or
#  * with a path to a specific file to be formated.
#

usage() {
    echo "Usage: /path/to/format-sources.sh [FILE]"
    echo "With no arguments all C++ and Java files (recursively) are reformatted."
    exit 1
}

reformat() {
    astyle \
      --suffix=none \
      --convert-tabs \
      $EXCLUDE \
      $RECURSIVE \
      --options=none \
      --add-brackets \
      --convert-tabs \
      --close-templates \
      --pad-oper \
      --pad-header \
      --unpad-paren \
      --align-pointer=type \
      --align-reference=type \
      --indent-preproc-define \
      --indent=spaces=4 \
      --formatted \
      "$@"
}

if [ -n "$1" ]; then
    [ "$1" == "-h" -o "$1" == "--help" ] && usage
    [ -f "$1" ] || usage
    echo "Formatting file '$1'..."
    echo "$1" | grep '.java' > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        reformat --style=java --mode=java "$1"
    else
        reformat --style=allman --mode=c "$1"
    fi
else
    echo "Format all C++ and Java files in the current directory? (Enter to continue, Ctrl-C to abort)"
    read
    RECURSIVE="--recursive"
    EXCLUDE="--exclude=third_party"
    reformat --style=allman --mode=c --recursive *.cc *.hh *.sc *.c *.cpp '*.h'
    reformat --style=java --mode=java --recursive *.java
fi

echo "Done."
