#!/usr/bin/env bash
set -euo pipefail

COMMIT_MSG_FILE=$1
MESSAGE=$(sed -n '1p' "$COMMIT_MSG_FILE")

# Allow merge commits and empty messages (handled by git).
if [[ "$MESSAGE" =~ ^Merge ]]; then
  exit 0
fi

CONVENTIONAL_COMMIT_REGEX='^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test|release)(\([a-z0-9\-]+\))?!?: .+'

if [[ ! $MESSAGE =~ $CONVENTIONAL_COMMIT_REGEX ]]; then
  cat <<'EOF'
Commit message does not follow Conventional Commits.
Expected format: type(optional-scope)!: summary

Examples:
  feat: add lossy_pow helper
  fix(parser): handle trailing underscores
  docs!: rewrite feature-flag section
EOF
  exit 1
fi

exit 0
