#! /bin/sh
#! /bin/sh --version
set -eu

setup() {
  file='.git/hooks/commit-msg'
  if ( test -f "$file" && grep_for_proofr "$file" )
  then
    echo 'proofr already setup'
  else
    echo "$0" '"$@" || exit $?' >> "$file"
    chmod u+x "$file"
  fi
}

grep_for_proofr () {
  grep --quiet '\bproofr\b' "$@"
}
#! /bin/sh --version
set -eu

if test 0 -eq "$#"
then
  echo 'Read the README'
  exit 1
fi

if test 'setup' = "$1"
then
  setup
  exit
fi

commit_message_file="$1"

cleanup_commit_message () {
  commit_message_file="$1"
  while read -r line
  do
    if test "$line" = '# ------------------------ >8 ------------------------'
    then
      return
    fi
    if test "$( echo "$line" | cut -c 1)" = '#'
    then
      continue
    fi
    echo "$line"
  done < "$commit_message_file"
}

commit_message="$(cleanup_commit_message "$commit_message_file")"
commit_message_subject="$(echo "$commit_message" | head -n 1 )"
commit_message_body="$(echo "$commit_message" | tail -n +2)"

# Pass if message is empty, exit early
test -z "$commit_message" && exit

grep_subject() {
  echo "$commit_message_subject" | grep --quiet "$1"
}

if grep_subject '^Merge '
then
  is_merge=true
else
  is_merge=false
fi

rule() {
  case $1 in
    1) echo Separate subject from body with a blank line ;;
    2) echo Limit the subject line to 50 characters ;;
    3) echo Capitalize the subject line ;;
    4) echo Do not end the subject line with a period ;;
    5) echo Use the imperative mood in the subject line ;;
    6) echo Wrap the body at 72 characters ;;
    7) echo Use the body to explain _what_ and _why_ vs. _how_ ;;
  esac
}

validate() {
  case $1 in
    1) # Message has one line, or second line is blank
      test    -z  "$(echo "$commit_message_body" | head -n 1)" ;;
    2) # Subject is no more than 51 characters (50 + newline)
      test 51 -ge ${#commit_message_subject} ||
      $is_merge ;;
    3) # Subject does not begin with lowercase letter
      ! grep_subject '^[a-z]' ;;
    4) # Subject does not end with a period
      $is_merge || ! grep_subject '\.\s*$' ;;
    5) # Subject does not begin with past tense
      ! grep_subject '^\w*ed\s' ;;
    6) # Body does not contain line longer than 73 characters
      echo "$commit_message_body" | while read -r line
      do
        test 73 -ge "${#line}" || return 1 # TODO this return shouldn't be required
      done ;;
  esac
}

calc_error_code() {
  echo $((1<<$1))
}

exit_code=0

for index in $(seq 6)
do
  validate "$index" && continue
  rule "$index"
  error_code=$(calc_error_code "$index")
  exit_code=$(( exit_code + error_code ))
done

exit "$exit_code"
