#!/bin/bash
# Copyright (c) 2014, Djaodjin Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Run code convention checks before accepting a commit

set -e

PYLINTRC=/etc/pylintrc
PYLINT=pylint

# We need to run pylint on actual files on the filesystem.
# That is where they will reside.
TEMPDIR=$(mktemp -d -t git-pre-receive.XXXXXXXXXX)
function finish {
  # Cleanup code here, gets executed on exit no matter what happened.
  /bin/rm -rf $TEMPDIR
}
trap finish EXIT

# Entry Point for the script
while read oldrev newrev refname
do
    echo -e "pre-receive $oldrev $newrev $refname"
    if [[ $refname = "refs/heads/master" ]]; then
        /usr/bin/git archive --format=tar $newrev | tar -C $TEMPDIR -xf -
        pushd $TEMPDIR
        MODULES=`find . -name '__init__.py' | cut -d '/' -f 2 | sort | uniq`
        if [ "X$MODULES" != "X" ] ; then
            echo -e "running analysis on $MODULES\n"
            $PYLINT --rcfile=$PYLINTRC $MODULES
            if [ $? -ne 0 ] ; then
                echo -e "\n$newrev does not pass pylint - push rejected."
                exit $rc
            fi
        else
            echo -e "warning: No Python modules in repository."
        fi
        popd
    fi
done

# If we get here, everything is good.
exit 0
