#!/bin/bash

if [ "$NO_PRECOMMIT_HOOK" = "1" ]; then exit 0; fi

STAGED_GO_FILES=$(git diff --cached --name-only | grep "\.go$")
STAGED_GO_DIRS=$(dirname ${STAGED_GO_FILES} | uniq)
if [[ "$STAGED_GO_FILES" = "" ]]; then
    exit 0
fi
GOPATH=${GOPATH:-$HOME/go}
GOIMPORTS=$GOPATH/bin/goimports
GOLINT=$GOPATH/bin/golint
PASS=true

# Check for goimports
if [[ ! -x "$GOIMPORTS" ]]; then
    printf "\t\033[41mPlease install goimports\033[0m (go get golang.org/x/tools/cmd/goimports)\n"
    PASS=false
fi

# Check for golint
if [[ ! -x "$GOLINT" ]]; then
    printf "\t\033[41mPlease install golint\033[0m (go get golang.org/x/lint/golint)\n"
    PASS=false
fi

if ! $PASS; then
    exit 1
fi

PASS=true

for FILE in $STAGED_GO_FILES; do
    # Run goimports on the staged file
    $GOIMPORTS -w "$FILE"

    # Run golint on the staged files and check the exit status
    lint_filters=(
        "should have comment or be unexported"
        "should have comment \(or a comment on this block\) or be unexported"
        "don't use ALL_CAPS in Go names; use CamelCase"
    )
    command="$GOLINT $FILE"
    for filter in "${lint_filters[@]}"; do
        command="$command | grep -v -E \"$filter\""
    done
    eval "$command"
    if [[ $? == 0 ]]; then
        printf "\t\033[31mgolint $FILE\033[0m \033[0;30m\033[41mFAILURE!\033[0m\n"
        PASS=false
    else
        printf "\t\033[32mgolint $FILE\033[0m \033[0;30m\033[42mpass\033[0m\n"
    fi
done

for DIR in $STAGED_GO_DIRS; do
    (
        cd $DIR
        go vet .
        if [[ $? == 1 ]]; then
            printf "\t\033[31mgovet $DIR\033[0m \033[0;30m\033[41mFAILURE!\033[0m\n"
            PASS=false
        else
            printf "\t\033[32mgovet $DIR\033[0m \033[0;30m\033[42mpass\033[0m\n"
        fi
    )
done

if ! $PASS; then
    printf "\033[0;30m\033[41mCOMMIT FAILED\033[0m\n"
    exit 1
else
    printf "\033[0;30m\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi

exit 0
