#!/bin/bash

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

# Path to executable
CL_BIN=/usr/local/bin/csslint

# Default file glob pattern
CL_FILE_PATTERN="\.(css)$"

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

# 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 $CL_BIN ]; then
	echo "Csslint bin not found or executable -> $CL_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 "$CL_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=$($CL_BIN $FILES_TO_CHECK)
RETVAL=$?

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

exit $RETVAL
