#!/bin/sh
# Rejects a commit whose message breaks the format described in CONTRIBUTING.
# Adds a Change-Id when the footer has none.
# The rules live in scripts/check-commit-message.

top=$(git rev-parse --show-toplevel) || exit 1

if ! "$top/scripts/check-commit-message" "$1"; then
    echo "commit-msg: see WRITING COMMITS in CONTRIBUTING" >&2
    echo "commit-msg: the message is kept in $1; retry with" \
        "'git commit -e -F $1'" >&2
    exit 1
fi

trailers=$(git interpret-trailers --parse "$1") || exit 1
if printf '%s\n' "$trailers" | grep -qi '^Change-Id:'; then
    exit 0
fi

change_id=$(od -An -N20 -tx1 /dev/urandom) || exit 1
change_id=$(printf '%s' "$change_id" | tr -d '[:space:]') || exit 1
if [ "${#change_id}" -ne 40 ]; then
    echo "commit-msg: cannot read 20 random bytes from /dev/urandom" >&2
    exit 1
fi

git interpret-trailers --in-place --trailer "Change-Id: I$change_id" "$1"
