#!/bin/sh -efu
#
# Copyright (c) 2020-2021 Vladimir D. Seleznev <vseleznv@altlinux.org>
#
# Calculate package identity.
#
# SPDX-License-Identifier: GPL-3.0-or-later
#

. shell-error
. shell-getopt
. shell-args

show_help()
{
	cat <<-EOF
	Usage: $PROG [options] <package> [<package> ...]

	Options:
	  --dbpath=DIRECTORY		use database in DIRECTORY;
	  -F CMD, --filter-cmd=CMD	pass payload to filter command;
	  -p, --package			calculate identity of package file;
	  -h, --help			show this text and exit.

	The filter command is used to filter the payload before calculating the
	RPMIdentity. It accepts stdin and produces output to stdout.

	Report bugs to http://bugzilla.altlinux.org/
	EOF
	exit "$@"
}

PROG=rpmidentity
TEMP="$(getopt -n "$PROG" -o F:,h,p -l filter-cmd:,dbpath:,help,package -- "$@")" ||
        show_usage 1 >&2
eval set -- "$TEMP"

filter_cmd=
opts=
while :; do
        case "$1" in
		--dbpath) shift; opts="${opts:+$opts }--dbpath=$1" ;;
		-F|--filter-cmd) shift; filter_cmd="$1" ;;
		-p|--package) opts="${opts:+$opts }-p" ;;
		-h|--help) show_help ;;
		--) shift; break ;;
        esac
	shift
done

if [ "$#" -eq 0 ]; then
	show_help 1 >&2
fi

TAGLIST='# Tag list for rpm identity calculation
# according to this discussion:
# https://lists.altlinux.org/pipermail/devel/2020-April/210672.html
# files
FILEFLAGS
FILEGROUPNAME
FILEINODES
FILELINKTOS
FILEMD5S
FILEMODES
FILENAMES
FILEUSERNAME
# dependencies
REQUIRENAME
REQUIREFLAGS
REQUIREVERSION
PROVIDENAME
PROVIDEFLAGS
PROVIDEVERSION
OBSOLETENAME
OBSOLETEFLAGS
OBSOLETEVERSION
CONFLICTNAME
CONFLICTFLAGS
CONFLICTVERSION
# pre-, post-, postun- and filetriggers
PREIN
PREINPROG
POSTIN
POSTINPROG
POSTUN
POSTUNPROG
PREUN
PREUNPROG
TRIGGERSCRIPTPROG
TRIGGERSCRIPTS
VERIFYSCRIPTPROG
VERIFYSCRIPT
'

# construct a query format string in the following form: "[tag:%{tag:shescape}\n]"
qf="$(printf %s "$TAGLIST" |sed -n -E 's/^([^#].*)$/[\1:%{\1:shescape}\\n]/p')"

tmpfile0=
tmpfile1=
cleanups()
{
	[ ! -f "$tmpfile0" ] || rm "$tmpfile0"
	[ ! -f "$tmpfile1" ] || rm "$tmpfile1"
	exit "$@"
}
trap 'cleanups $?' EXIT
trap 'cleanups 143' HUP INT TERM QUIT
tmpfile0="$(mktemp --suffix=rpmidentity)"

ret=0
for pkg; do
	if ! rpmquery $opts --qf "$qf" -- "$pkg" >"$tmpfile0"; then
		message "Cannot calculate package identity of $pkg"
		ret=1
		continue
	fi

	sed -i '/^$/d' "$tmpfile0"

	disttag="$(rpmquery $opts --qf '%|disttag?{%{disttag}}|' -- "$pkg")"
	if [ -n "$disttag" ]; then
		quote_sed_regexp_variable sed_disttag "$disttag"
		sed -i "/^[[:alpha:]]\+VERSION/{s/:$sed_disttag//}" "$tmpfile0"
	fi

	if [ -n "$filter_cmd" ]; then
		tmpfile1="$(mktemp --suffix=rpmidentity)"
		"$filter_cmd" < "$tmpfile0" > "$tmpfile1"
		tmpfile="tmpfile1"
	else
		tmpfile="$tmpfile0"
	fi

	printf '%s\t%s\n' \
		"$pkg" \
		"$(set -- $(b2sum "$tmpfile"); echo "$1")"
done

exit "$ret"
