#!/bin/bash
#---------------------------------*- sh -*-------------------------------------
# =========                 |
# \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
#  \\    /   O peration     | Website:  https://openfoam.org
#   \\  /    A nd           | Copyright (C) 2011-2018 OpenFOAM Foundation
#    \\/     M anipulation  |
#------------------------------------------------------------------------------
# License
#     This file is part of OpenFOAM.
#
#     OpenFOAM 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.
#
#     OpenFOAM 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 OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.
#
# Script
#     pre-receive-hook
#
# Description
#     pre-receive hook for git.
#     Copy or link this file as ".git/hooks/pre-receive"
#
#     Eg,
#     (
#         cd $WM_PROJECT_DIR/.git/hooks &&
#         ln -sf ../../bin/tools/pre-receive-hook pre-receive
#     )
#
#     Hook receives: <old-sha1> <new-sha1> <ref-name>
#
#     Checks for
#     - illegal code, e.g. <TAB>
#     - columns greater than 80 for *.[CH] files
#
#------------------------------------------------------------------------------

. bin/tools/HookFunctions || exit 1

hookName="pre-receive"


#------------------------------------------------------------------------------
# Main code. Do all checks.
#

while read oldSHA1 newSHA1 refName
do
    unset fileList rawFileList

    if [ "$newSHA1" = 0 ]
    then
        # Ref to be deleted
        continue
    elif [ "$oldSHA1" = 0 ]
    then
        # Ref to be created
        rawFileList=$(git diff-tree --root $newSHA1)
    else
        # Normal changes
        rawFileList=$(git diff --name-only $oldSHA1..$newSHA1)
    fi

    # No files have changed, so the checks are not necessary
    [ -n "$rawFileList" ] || continue

    fileList=$(
    for f in $rawFileList
    do
        git cat-file -e $newSHA1:$f > /dev/null 2>&1 && echo "$f"
    done
    )

    # check for illegal code, e.g. <TAB>, etc
    checkIllegalCode $newSHA1

    # ensure code conforms to 80 columns max
    checkLineLengthNonDirective $newSHA1

done

exit 0

#------------------------------------------------------------------------------
