#!/bin/bash
# Git hook for roughly checking commit messages against Conventional Commits
#

# get the first line of the commit message
INPUT_FILE=$1
START_LINE=$(head -n1 "$INPUT_FILE")

# return early if no linting is required
if [[ $START_LINE =~ \[no-lint\] ]]; then
   exit 0
fi

# initialize config
types=(
	"build"
	"docs"
	"feat"
	"fix"
	"perf"
	"refactor"
	"style"
	"test"
	"chore"
	"WIP"
)
min_length=10
max_length=52

# build the regex pattern based on the config file
function build_regex() {
  # allow revert commits
	regexp="^((([Rr]evert|[Mm]erge): ?)|(("
	# add types
  for type in "${types[@]}"
  do
    regexp="${regexp}$type|"
  done
  # add optional scope
  regexp="${regexp%|})(\(.*\))?!?:)) "
	#	add length requirement
  extended_regexp="${regexp}(.{$min_length,$max_length})$"
}

# Print out a message explaining what's wrong
function print_error() {
  commit_message=$1
  commit_message_length=$(( $(echo "$commit_message" | cut -d':' -f2 | xargs | wc -c) - 1))

  if ((commit_message_length<min_length)); then too_short=true; else too_short=false; fi
  if ((commit_message_length>max_length)); then too_long=true; else too_long=false; fi
  if [[ ! $START_LINE =~ $regexp ]]; then bad_type=true; else bad_type=false; fi

  echo -e "\n\e[1m\e[31m[Invalid Commit Message]"
  echo -e "------------------------\033[0m\e[0m"
	echo -e "\e[37mCommit message: \e[33m\"$commit_message\"\033[0m";
	if $bad_type; then echo -e "Valid types: \e[36m${types[@]} revert\033[0m"; fi
  if $too_short; then echo -e "Min length: \e[36m$min_length\033[0m \e[37mActual length: \e[33m$commit_message_length\033[0m"; fi
  if $too_long; then echo -e "Max length: \e[36m$max_length\033[0m \e[37mActual length: \e[33m$commit_message_length\033[0m"; fi
}

build_regex

if [[ ! $START_LINE =~ $extended_regexp ]]; then
  print_error "$START_LINE"
  exit 1
fi
