#!/bin/sh
set -eu

message_file=$1
subject=$(grep -v '^#' "$message_file" | sed -n '1p')

case "$subject" in
  "Merge "* | "Revert \""* | "fixup! "* | "squash! "* | "amend! "*)
    exit 0
    ;;
esac

types='feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert'
pattern="^($types)(\([A-Za-z0-9._/-]+\))?!?: [^ ].*[^ .]$"

if ! printf '%s\n' "$subject" | grep -Eq "$pattern"; then
  printf 'commit-msg: the first line must follow Conventional Commits.\n' >&2
  printf '  Format:  type(scope): summary\n' >&2
  printf '  Types:   %s\n' "$(printf '%s' "$types" | tr '|' ' ')" >&2
  printf '  Example: fix(auth): reject expired reset tokens\n' >&2
  printf '  Got:     %s\n' "$subject" >&2
  exit 1
fi

length=${#subject}
if [ "$length" -gt 72 ]; then
  printf 'commit-msg: the first line is %s characters. Keep it to 72 or fewer.\n' "$length" >&2
  exit 1
fi

exit 0
