#!/bin/sh -efu
#
# Copyright (C) 2000-2005, 2011  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2022  Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>
#
# Generates timestamp for rpm specfile changelog entry.
#
# 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-stamp-spec

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

trap '' PIPE

USAGE()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
safe-stamp-spec - generates timestamp for rpm specfile changelog entry.

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

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

Valid options are:
-h, --help                              show this text.
EOF
	[ -n "$1" ] && exit "$1" || exit
}

TEMP="$(getopt -n "$PROG" -o h -l help -- "$@")" || USAGE
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) USAGE 0
			;;
		--) shift; break
			;;
		*) echo "$PROG: unrecognized option: $1" >&2; exit 1
			;;
	esac
done

[ -n "$*" ] || USAGE

p="$(rpm --eval '%{?packager}')"
if [ -z "$p" ]; then
	env="$(hsh --printenv)"
	# shellcheck disable=SC2086
	[ -z "$env" ] ||
		p="$(eval $env 2>/dev/null; echo "${packager:-}")"
fi
if [ -z "$p" ]; then
	echo 'Configuration error: undefined packager' >&2
	exit 1
fi
d=$(LC_TIME=C date '+%a %b %d %Y')

for spec; do
	description="$(describe-specfile --epoch "$spec")"
	# shellcheck disable=SC2086
	set -- $description
	# shellcheck disable=SC2034
	pkg="$1"; shift
	ver="$1"; shift
	rel="$1"; shift
	printf '* %s %s %s\n' "$d" "$p" "$ver-$rel"
done
