#!/bin/sh -efu
#
# Copyright (C) 2000-2011  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2022  Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>
#
# Generates and adds changelog entry to rpm specfile.
#
# 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

# shellcheck enable=all disable=SC2250

PROG=safe-add-changelog

# shellcheck source=/bin/shell-error
. shell-error
# shellcheck source=/bin/shell-quote
. shell-quote

STAMPER=safe-stamp-spec
ENTRY='- '
NOCHECK=

USAGE()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
safe-add-changelog - generates and adds changelog entry to rpm specfile.

safe-add-changelog is free software, covered by the GNU General Public License.
safe-add-changelog comes with ABSOLUTELY NO WARRANTY, see license for details.

Usage: $PROG [options] <specfile> [ <specfile>]*

Valid options are:
-s STAMPER, --stamper=STAMPER           STAMPER executable;
-e entry, --entry=entry                 changelog entry text;
--nocheck                               do not check specfile versions;
-h, --help                              show this text.

Configured STAMPER executable is $STAMPER;
Configured changelog entry is '$ENTRY'.
EOF
	[ -n "$1" ] && exit "$1" || exit
}

TEMP="$(getopt -n "$PROG" -o a:e:r:s:h -l entry:,stamper:,nocheck,help -- "$@")" || USAGE
eval set -- "$TEMP"

while :; do
	case "$1" in
		-e|--entry) shift; ENTRY="$1"; shift
			;;
		-s|--stamper) shift; STAMPER="$1"; shift
			;;
		--nocheck) NOCHECK=1; shift
			;;
		-h|--help) USAGE 0
			;;
		--) shift; break
			;;
		*) echo "$PROG: unrecognized option: $1" >&2; exit 1
			;;
	esac
done

[ -n "$*" ] || USAGE

exitcode=

quote_shell_variable STAMPER "$STAMPER"

for spec in "$@"; do
	if [ ! -r "$spec" ]; then
		echo "$PROG: $spec: not available, skipping"
		exitcode=1
		continue
	fi
	qspec=
	quote_shell_variable qspec "$spec"
	stamp="$(eval "\"$STAMPER\" \"$qspec\"")"
	if [ -z "$NOCHECK" ]; then
		oldstamp="$(awk '/^%changelog$/{c=1;next} c{print $0; exit}' "$spec")"
		if [ "$oldstamp" = "$stamp" ]; then
			echo "$PROG: $spec: version unchanged, skipping"
			exitcode=1
			continue
		fi
	fi
	if [ -n "$stamp" ]; then
		cat << __EOF__EOF__EOF__ | paste_changelog "$spec"
$stamp
$ENTRY

__EOF__EOF__EOF__
	fi
done

# shellcheck disable=SC2248
exit $exitcode
