#!/usr/bin/env bash
# Enforce Conventional Commit subjects so the history is machine-readable.
#
# Bypass with: git commit --no-verify   or   SKIP_PHOEBUS_HOOKS=1 git commit ...

set -uo pipefail

[[ "${SKIP_PHOEBUS_HOOKS:-0}" == "1" ]] && exit 0

msg_file="${1:?commit message file}"
subject="$(grep -v '^#' "$msg_file" | sed '/^[[:space:]]*$/d' | head -n 1)"

if [[ -z "$subject" ]]; then
    echo "commit-msg: empty commit message" >&2
    exit 1
fi

# Permit generated/merge/revert subjects.
case "$subject" in
    Merge\ *|Revert\ *|fixup!\ *|squash!\ *) exit 0 ;;
esac

if ! [[ "$subject" =~ ^(feat|fix|refactor|perf|test|docs|build|ci|chore|revert)(\([a-z0-9._/-]+\))?!?:\ .+ ]]; then
    cat >&2 <<'EOF'
commit-msg: subject must be a Conventional Commit, e.g.

  feat(rust): add typed SystemAction broker
  fix(executor): make the getuto keyring readable by the verify user
  docs(git): record the Forgejo remote and clone/setup steps

Types: feat fix refactor perf test docs build ci chore revert
Bypass with: git commit --no-verify
EOF
    exit 1
fi

if (( ${#subject} > 72 )); then
    echo "commit-msg: subject is ${#subject} chars; keep it <= 72" >&2
    exit 1
fi

exit 0
