#!/usr/bin/env bash

if [ -f "$1" ]; then
    readonly FIRST_ARGUMENT=$(<"$1")
else
    readonly FIRST_ARGUMENT="$1"
fi
readonly MIN_TITLE_WORD_COUNT=4
readonly ERROR=1
readonly OK=0

declare -a RESULTS
declare -a VALIDATIONS
showError=false

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

if grep -qi "lint fix" <<< "$FIRST_ARGUMENT"; then
    echo "You should not have been able to commit a lint error." 1>&2
    echo -n "Installing your githooks for you..." 1>&2
    # shellcheck disable=SC1090
    exec "$(git rev-parse --show-toplevel)/scripts/setup_hooks"
    echo "Done." 1>&2
    exit "$ERROR"
fi

add_result() {
    hasError="$2"

    VALIDATIONS+=("$1")
    RESULTS+=("$hasError")

    if [ "$hasError" = true ]; then
        showError=true
    fi
}

# commit validations
TITLE_WORD_COUNT=$(echo "$FIRST_ARGUMENT" | head -1 | wc -w | tr -d '[:space:]')
add_result "A title with at least $MIN_TITLE_WORD_COUNT words (count: $TITLE_WORD_COUNT)" \
   "$([ "$TITLE_WORD_COUNT" -ge "$MIN_TITLE_WORD_COUNT" ] && echo false || echo true)"

EMPTY_SECOND_LINE=$(grep -v '^#' <<< "$FIRST_ARGUMENT" | tail -n +2 | head -1 | tr -d '[:space:]')
add_result "An empty second line" \
   "$([ -z "$EMPTY_SECOND_LINE" ] && echo false || echo true)"

# render errors
if [ "$showError" = true ]; then
    echo
    echo "$(tput bold)Please write a descriptive commit message:$(tput sgr0)" 1>&2

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