#!/bin/sh -efu
#
# Copyright (c) 2020 Dmitry V. Levin <ldv@altlinux.org>
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-or-later

. shell-error

: "${ALT_GPG_KEYS_DIR:=/usr/lib/alt-gpgkeys}"
: "${ALT_RPM_KEYS_DIR:=/usr/lib/alt-rpmkeys}"

file="$1"; shift

if type rpmkeys >/dev/null 2>&1; then
	# new rpm
	sig_text="$(rpmkeys -v --checksig --dbpath "$ALT_RPM_KEYS_DIR" -- "$file")" || {
		[ -z "$sig_text" ] ||
			printf >&2 '%s\n' "$sig_text"
		fatal "$file: signature verification failed"
	}

	keyid="$(printf %s "$sig_text" |
		sed -n 's/^[[:space:]]*V[[:digit:]]\+ [[:alpha:]]\+\/[[:alpha:]][[:alnum:]]* Signature, key ID \([[:xdigit:]]\+\): OK$/\1/p')"
else
	# old rpm
	sig_text="$(rpmsign -v --checksig -- "$file")" || {
		[ -z "$sig_text" ] ||
			printf >&2 '%s\n' "$sig_text"
		fatal "$file: signature verification failed"
	}

	keyid="$(printf %s "$sig_text" |
		sed -n 's/^gpg: Signature made .* using .* key ID \([[:xdigit:]]\+\)$/\1/p')"
fi

set -- $keyid
case $# in
	0) fatal "$file: signature not found" ;;
	1) ;;
	*) fatal "$file: too many signatures found ($#)" ;;
esac

signer="$(gpg --homedir "$ALT_GPG_KEYS_DIR" --list-keys -- "$keyid" 2>/dev/null |
	sed '/^uid[[:space:]]\+/!d;s///;q')"
[ -n "$signer" ] ||
	fatal "$file: signature key ID $keyid not found"

printf '%s\n' "$signer"
