#!/usr/bin/env sh

# Copyright (c) 2018-2022, 2024 Free Software Foundation, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

set -e
set -u

AUTHOR=$(git log -n1 --format='%aN')
EMAIL=$(git log -n1 --format='%aE')
DOMAIN=$(echo "$EMAIL" | cut -d'@' -f2)
EMAIL_PARSE=$(echo "$EMAIL" | sed 's/@/ \\[at\\] /g')

retval=0

echo "The last commit is made by $AUTHOR: $EMAIL_PARSE"

if git cat-file -p HEAD | grep "^Copyright-paperwork-exempt: Yes"; then
	echo "This work is copyright paperwork exempt."
elif ! grep -E -q "^\\[ASSGN\\] .* \\*($EMAIL_PARSE|$DOMAIN)\\*$" AUTHORS; then
	if grep -E -q "^\\[ *\\] .* \\*($EMAIL_PARSE|$DOMAIN)\\*$" AUTHORS; then
		echo "The author is known, but did not yet complete the FSF Copyright Assignment."
	else
		echo "The author was not found in the AUTHORS file."
		echo "Has the author completed the FSF Copyright Assignment?"
	fi
	echo
	echo "If the commit is minor, please add this to the commit message:"
	echo "Copyright-paperwork-exempt: Yes"
	retval=1
else
	echo "The author or company was found in the AUTHORS file."
	echo "This work may be merged into master"
fi

exit $retval
