#!/usr/bin/env bash

if cat $1 | grep -qi "Player release:"; then
    exit 0
fi

# some application contexts have a $TERM of 'dumb' which cannot render colors from `tput`
if [[ "$TERM" == "dumb" ]]; then
    export TERM="vanilla"
fi

OK=0
declare -a RESULTS
declare -a VALIDATIONS

add_result() {
    VALIDATIONS+=("$1")
    RESULTS+=($2)

    if [ $2 -ne 0 ]; then
        OK=1
    fi
}

if cat $1 | grep -qi "lint fix"; then
    echo "You should not have been able to commit a lint error." 1>&2
    echo -n "Installing your githooks for you..." 1>&2
    . `git rev-parse --show-toplevel`/scripts/setup_hooks
    echo " Done." 1>&2
    exit 1
fi

add_result "A title with at least 5 words" \
    $([ `cat $1 | head -1 | wc -w` -ge 5 ]; echo $?)

add_result "An empty second line" \
    $([ -z `cat $1 | grep -v '^#' | tail -n +2 | head -1` ]; echo $?)

add_result "A message that isn't entirely useless" \
    $([ -z "`cat $1 | grep -ie 'pr change' -e 'cr change'`" ]; echo $?)

if [ $OK -ne 0 ]; then
    echo
    echo "$(tput bold)Please write a decent commit message. A decent commit message has:$(tput sgr0)" 1>&2

    for i in "${!RESULTS[@]}"; do
        if [ "${RESULTS[$i]}" -eq 0 ]; then
            echo "$(tput setaf 2)  [ ✓ ]  ${VALIDATIONS[$i]}" 1>&2
        else
            echo "$(tput setaf 1)  [ ✗ ]  ${VALIDATIONS[$i]}" 1>&2
        fi
    done
    echo "$(tput sgr0)" 1>&2
fi

exit $OK
