#!/bin/sh -efu
#
# Copyright (C) 2006-2007  Alexey Gladkov <legion@altlinux.org>
# Copyright (C) 2006-2007  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2006  Sergey Vlasov <vsu@altlinux.org>
#
# git commit wrapper for gear.
#
# This file 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

. gear-sh-functions

rules="${RULES-}"
main_tree_id=${TREE_ID:-HEAD}
commitlog=

workdir=
exit_handler()
{
	local rc=$?
	trap - EXIT
	[ -z "$workdir" ] || rm -rf -- "$workdir"
	exit $rc
}

print_version()
{
	cat <<EOF
$PROG version $PROG_VERSION
Written by Alexey Gladkov <legion@altlinux.org>

Copyright (C) 2006-2007  Alexey Gladkov <legion@altlinux.org>
Copyright (C) 2006-2007  Dmitry V. Levin <ldv@altlinux.org>
Copyright (C) 2006  Sergey Vlasov <vsu@altlinux.org>
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
EOF
	exit
}

case "${*-}" in
	-V|--version)
		print_version
		;;
	-h|--help)
		git-commit --help |
			sed "s|\(/usr/bin/\)\?git-commit|$PROG [--spec=<file>]|g"
		exit
		;;
esac

# Change to toplevel directory
chdir_to_toplevel

if [ $# -gt 0 ] && [ "$*" != "${*#--spec[= ]}" ]; then
	case "$1" in
	    --spec=*) specfile="${1#*=}"
		shift
		;;
	    --spec) shift
		[ "$#" -gt 0 ] ||
			fatal "option requires an argument: --spec"
		specfile="$1"
		shift
		;;
	esac
	[ -f "$specfile" -o -z "$specfile" ] ||
		fatal "$specfile: file not available"
elif git cat-file -t "$main_tree_id" >/dev/null 2>&1; then
	trap exit_handler HUP INT QUIT TERM EXIT
	workdir="$(mktemp -dt "$PROG.XXXXXXXXXX")"

	# Get specfile from archive.
	find_specfile

	rm -rf -- "$workdir"
	trap - HUP INT QUIT TERM EXIT
	unset rules main_tree_id workdir
else
	specfile="$(set +f; find_specfile_in_cwd '' *)" ||:
fi

if [ -f "$specfile" ]; then
	vr="$(sed -ne '/^[[:space:]]*%changelog[[:space:]]*$/{n; s/\* .* \([^[:space:]]\+\)$/\1/p}' "$specfile")"
	ch="$(sed -ne '0,/^[[:space:]]*%changelog[[:space:]]*$/d;2,/^* /{/^* /!p}' "$specfile")"
	commitlog="${vr:+$vr}

$ch"
	unset ch vr specfile
fi

exec git commit ${commitlog:+-m "$commitlog" --edit} "$@"
