#!/bin/bash

##################################################################################
# Override any of these in the config file

# Path to executable
YL_BIN=/usr/local/bin/yamllint

# Default file glob pattern
YL_FILE_PATTERN="\.(yml|yaml)$"

##################################################################################

# parse config
CONFIG_FILE=$(dirname $0)/config
if [ -e $CONFIG_FILE ]; then
    . $CONFIG_FILE
fi

# simple check if executable is set up correctly
if [ ! -x $YL_BIN ]; then
    echo "Yamllint bin not found or executable -> $YL_BIN"
    exit 1
fi

# stolen from template file
if git rev-parse --verify HEAD
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# this is the magic: retrieve all files in staging area that
# are added, modified or renamed but no deletions etc
FILES=$(git diff-index --name-only --cached --diff-filter=ACMR $against -- )

if [ "$FILES" == "" ]; then
    exit 0
fi

# match files against whitelist
FILES_TO_CHECK=""
for FILE in $FILES
do
    echo "$FILE" | egrep -q "$YL_FILE_PATTERN"
    RETVAL=$?
    if [ "$RETVAL" -eq "0" ]
    then
        FILES_TO_CHECK="$FILES_TO_CHECK $FILE"
    fi
done

if [ "$FILES_TO_CHECK" == "" ]; then
    exit 0
fi

OUTPUT=$($YL_BIN -s $FILES_TO_CHECK)
RETVAL=$?

if [ $RETVAL -ne 0 ]; then
    echo "$OUTPUT"
fi

exit $RETVAL
