#!/usr/bin/env sh
#
# ----------------------------------------------------------------------------
#
# Copyright 2019 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ----------------------------------------------------------------------------
#

# Pre-commit git hook
# Performs following steps:
# - clang-format all source files staged for commit
# These flags are available:
# - hooks.noautoformat: Disable autoformat
# To install this hook copy it to .git/hooks

noautoformat=$(git config hooks.noautoformat)
noshellcheck=$(git config hooks.noshellcheck)

if [ "$noautoformat" != "true" ]
then
    clang-format --version >/dev/null 2>&1
    fmt_installed=$?
    
    if [ "$fmt_installed" != "0" ]
    then
        echo "Error: clang-format is not installed"
        echo
        echo "Either install clang-format or disable auto formatting:"
        echo 
        echo "   git config hooks.noautoformat true"
        echo
        exit 1
    fi

    set -eu
    
    # Get all changed source files: *.h *.c *.hpp *.cpp
    changed_files=$(git diff --cached --name-only | awk '/\.[ch](pp)?$/')
    [ "$changed_files" = "" ] && exit 0
    echo $changed_files | awk 'END{print "-- Formatting "NF" file"(NF>1?"s":"")}'
    clang-format -i $changed_files
    git add $changed_files
fi

if [ "$noshellcheck" != "true" ]
then
    shellcheck --version >/dev/null 2>&1
    chk_installed=$?
    
    if [ "$chk_installed" != "0" ]
    then
        echo "Error: shellcheck is not installed"
        echo
        echo "Either install ShellCheck or disable shellchecking:"
        echo 
        echo "   git config hooks.noshellcheck true"
        echo
        exit 1
    fi

    set -eu
    
    for script in $(find . -not \( -path "./build/*" \) -name "*.sh")
    do
        shellcheck -x "$script"
    done
fi
