#!/bin/sh
# Source validation pre-commit hook
#
# Adapted from the source validation pre-commit hook used in Peloton.
# (see https://github.com/cmu-db/peloton/blob/master/script/git-hooks/pre-commit)
#
# This script collects all modified files and runs it through our source code
# validation script. The validation script returns 0 on success and 1 on any
# failure. This script can also run the server and controller tests by
# uncommenting lines 26-28 and 31-33, respectively. 
#
# To enable, symlink this file to '.git/hooks/pre-commit' like so:
#   cd $OTTERTUNE_DIR/.git/hooks
#   ln -s ../../script/git-hooks/pre-commit ./pre-commit


FILES=$(git diff --name-only --cached --diff-filter=d | grep -E '*\.(py|java)$')

WEBSITE_TESTS_RESULT=0
ANALYSIS_TESTS_RESULT=0
CONTROLLER_TESTS_RESULT=0
VALIDATOR_RESULT=0

if [ -n "$FILES" ]; then

    # Uncomment to run the website tests
    # cd server/website && python3 manage.py test --noinput -v 2
    # WEBSITE_TESTS_RESULT=$?
    # cd ../..

    # Uncomment to run the analysis tests
    # cd server && python3 -m unittest discover -s analysis/tests -v
    # ANALYSIS_TESTS_RESULT=$?
    # cd ..

    # Uncomment to run the controller tests
    # cd controller && gradle build -q
    # CONTROLLER_TESTS_RESULT=$?
    # cd ..

    # Run source code validator
    python3 script/validators/source_validator.py $FILES
    VALIDATOR_RESULT=$?

    if [ "$VALIDATOR_RESULT" -ne 0 ] || [ "$WEBSITE_TESTS_RESULT" -ne 0 ] || [ "$ANALYSIS_TESTS_RESULT" -ne 0 ] || [ "$CONTROLLER_TESTS_RESULT" -ne 0 ]; then

        echo " +------------------------------------------------------------+"
        echo " |                                                            |"
        echo " |                OTTERTUNE PRE-COMMIT HOOK                   |"
        echo " |                                                            |"
        echo " +------------------------------------------------------------+"
        echo ""

        if [ "$WEBSITE_TESTS_RESULT" -ne 0 ]; then
            echo " FAILED website tests!"
            echo ""
        fi

        if [ "$ANALYSIS_TESTS_RESULT" -ne 0 ]; then
            echo " FAILED analysis tests!"
            echo ""
        fi

        if [ "$CONTROLLER_TESTS_RESULT" -ne 0 ]; then
            echo " FAILED controller tests!"
            echo ""
        fi

        if [ "$VALIDATOR_RESULT" -ne 0 ]; then
            echo " FAILED source validation!"
            echo ""
            echo " Use the formatting script to help format all changed files:"
            echo " (ottertune/script/formatting/formatter.py)"
            echo ""
            echo "      \"python formatter.py --staged-files\""
            echo ""
        fi

        echo " To temporarily bypass the pre-commit hook, use:"
        echo ""
        echo "      \"git commit --no-verify\""
        echo
        echo " Be aware that changed files have to be staged again!"

        exit 1
    fi

fi

exit 0