#!/bin/sh
# Add a Change-Id to the commit message footer if it has none.

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"
