#!/bin/bash
#
# mk-authors - Update the s390-tools authors file (AUTHORS.md)
#
# Invocation examples:
#
#  $ mk-authors
#  $ mk-authors -t v2.0.0
#
# Copyright IBM Corp. 2017
#
# s390-tools is free software; you can redistribute it and/or modify
# it under the terms of the MIT license. See LICENSE for details.

cmd=$(basename $0)
authors_file="AUTHORS.md"

cleanup()
{
	test -f $authors_file_tmp && rm -f $authors_file_tmp
}
trap cleanup EXIT

#
# Print usage information
#
print_usage()
{
	cat <<EoUSAGE
Usage: $cmd [-t LAST_GIT_TAG]

Add all new authors since last release to the $authors_file file. Without
the -t option the tool uses the last available git tag as last release.

The tool runs on the s390-tools master branch.

OPTIONS
-t, --tag LAST_GIT_TAG  Use git tag LAST_GIT_TAG as starting point
-h, --help              Print this help, then exit
EoUSAGE
}

#
# Print help hint for option parsing error
#
print_parse_error_and_exit()
{
	echo "Try '$cmd -h' for more information." >&2
	exit 1
}

#
# Parse options
#
opts=$(getopt -o ht: -l help,tag: -n $cmd -- "$@")
if [ $? != 0 ]; then
	print_parse_error_and_exit
fi
# Use eval to remove getopt quotes
eval set -- $opts
while [ -n $1 ]; do
	case $1 in
	-h | --help)
		print_usage
		exit 0
		;;
	-t | --tag)
		release_tag_last=$2
		shift 2
		;;
	--)
		shift
		break
		;;
	*)
		break
		;;
	esac
done

if [ $# != 0 ]; then
	echo "$cmd: Invalid argument $1" >&2
	print_parse_error_and_exit
fi

#
# Get git root and last release tag
#
git_root=$(git rev-parse --show-toplevel 2> /dev/null)
if [ $? -ne 0 ]; then
	echo "$cmd: Use tool within s390-tools git repository" >&2
	print_parse_error_and_exit
fi
authors_file_path=$git_root/$authors_file
# Get last release tag if not specified via -t
if [ -z $release_tag_last ]; then
	tag_commit=$(git rev-list --tags --max-count=1)
	release_tag_last=$(git describe --tags $tag_commit)
fi
# Verify release tag
git show $release_tag_last &> /dev/null
if [ $? -ne 0 ]; then
	echo "$cmd: Cannot find tag '$release_tag_last'" >&2
	print_parse_error_and_exit
fi

#
# Update authors file
#

# Create temporary file for new author list
authors_file_tmp=$(mktemp /tmp/authors.XXXXXX)

echo "$cmd: Adding new authors since tag: $release_tag_last"
{
	# Print authors list without header
	tail -n +4 $authors_file_path
	# Add the new authors
	git log --format="- %an" $release_tag_last..master
	# Then sort everything and remove duplicates
} | sort | uniq > $authors_file_tmp
# Create new AUTHORS file with header ...
cat <<EoHEADER > $authors_file_path
List of all individuals having contributed content to s390-tools
----------------------------------------------------------------

EoHEADER
# ... and add new content
cat $authors_file_tmp >> $authors_file_path

cat <<EoUPDATE_MSG
 - Updated file: $authors_file_path
 - Verify changes with: git diff $authors_file_path
 - Do a manual *cleanup* before commiting if necessary.
EoUPDATE_MSG
