#!/bin/bash

fileName="$1"
lineNumber=0
maxWidth=72

error() {
    echo "$1"
    exit 1
}

while read -r line
do

    # Ignore comment lines (don't count line number either)
    [[ "$line" =~ ^#.* ]] && continue
    let lineNumber+=1
    length=${#line}

    # Subject line tests

    if [[ $lineNumber -eq 1 ]]; then

        [[ $length -gt $maxWidth ]] && \
        error "Limit the subject line to $maxWidth characters"

        [[ "$line" == *. ]] && \
        error "Do not end the subject line with a period"

        [[ ! "$line" =~ ^(feat|fix|docs|style|refactor|test|chore)(\([a-z]+\))?\:[[:space:]] ]] && \
        error "You must prefix the commit message with <feat|fix|docs|style|refactor|test|chore>(category)?: "

        [[ ! "$line" =~ ^(feat|fix|docs|style|refactor|test|chore)(\([a-z]+\))?\:[[:space:]][A-Z].*$ ]] && \
        error "Capitalise the subject line message - e.g. \"style: Remove whitespace\""
    fi

    # Rules related to the commit message body

    [[ $lineNumber -eq 2 ]] && [[ -n $line ]] && error "Separate subject from body with a blank line"

    [[ $lineNumber -gt 1 ]] && [[ $length -gt $maxWidth ]] && error "Wrap the body at $maxWidth characters"

done < "$fileName"

exit 0
